问题描述
我正在尝试将pyppeteer集成到flask应用程序中.我有运行pyppeteer并捕获页面截图的python脚本.如果我单独运行该脚本,则此文件为工作文件.
I am trying to integrate pyppeteer in a flask app. I have python script that runs pyppeteer and takes a screenshot of a page.This is working file if I run the script individually.
问题是在FLASK APP中运行该脚本时不起作用的脚本.
The PROBLEM is the same script does not work when i run it in a FLASK APP.
我收到以下错误:
loop.run_until_complete(capture(url, 123123))
File "/usr/local/Cellar/python/3.7.0/Frameworks/Python.framework/
Versions/3.7/lib/python3.7/asyncio/base_events.py",
line 568, in run_until_complete
return future.result()
File "/App-path/flaskr/image_capture/__init__.py", line 6, in capture
browser = await launch()
File "/usr/local/lib/python3.7/site-packages/pyppeteer/launcher.py",
line 311, in launch
return await Launcher(options, **kwargs).launch()
File "/usr/local/lib/python3.7/site-packages/pyppeteer/launcher.py",
line 180, in launch
signal.signal(signal.SIGINT, _close_process)
File"/usr/local/Cellar/python/3.7.0/Frameworks/Python.framework/
Versions/3.7/lib/python3.7/signal.py", line 47, in signal
handler = _signal.signal(_enum_to_int(signalnum),
_enum_to_int(handler))
ValueError: signal only works in main thread.
以下代码用于捕获屏幕截图.
The following code is used to capture screenshot.
async def capture(code_url, codeId):
browser = await launch()
# print('Hello')
page = await browser.newPage()
await page.setContent('<div id="chart-container">ABCD</div>')
# print(await page.content())
await page.addScriptTag({'url':'''{code_url}'''})
await page.waitFor('.animateon')
await page.setViewport({
'width':await
page.evaluate('''document.documentElement.clientWidth''') ,
'height': await
page.evaluate('''document.documentElement.clientHeight'''),
'deviceScaleFactor': 10,
})
await page.screenshot({'path': '''./temp/screenshot/chart-
{codeId}.jpg''', 'type': 'jpeg'})
await browser.close()
下面的代码是调用此方法的地方:
The following code is where this method is called :
@app.route('/api/v1/screenshot', methods=["POST"])
def screenShot():
url = request.form['url']
loop.run_until_complete(capture(url, 123123))
return jsonify("Image captured Successfully!")
我正在使用asyncio循环来处理异步捕获功能.
I am using asyncio loop to handle the async capture function.
另外,根据Stackoverflow问题的一些建议,我已经关闭了调试模式.
Also as per some suggestion from Stackoverflow questions I have turned off the debugging mode.
请建议我要去哪里了.
Python版本:3.7
Python Version : 3.7
推荐答案
您需要在禁用信号处理的情况下调用launch,
You need to call launch with disabled signals handling,
browser = await launch(
handleSIGINT=False,
handleSIGTERM=False,
handleSIGHUP=False
)
这篇关于在FLASK中运行pypupeteer会产生ValueError:信号仅在主线程中有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!