Running pypupeteer in FLASK gives ValueError: signal only works in main thread

Running pypupeteer in FLASK gives ValueError: signal only works in main thread

我正在尝试将 pyppeteer 集成到 Flask 应用程序中。我有 python 脚本 运行s pyppeteer,如果我单独 运行 脚本,我会截取 page.This 正在工作的文件。

问题 当我在 FLASK 应用程序中 运行 时,同一个脚本不起作用。

我收到以下错误:

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.

以下代码用于截图。

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()

调用此方法的代码如下:

@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!")

我正在使用异步循环来处理异步捕获功能。

另外,根据 Whosebug 问题的一些建议,我关闭了调试模式。

请指出我哪里出错了。

Python 版本:3.7

您需要在禁用信号处理的情况下调用启动,

browser = await launch(
    handleSIGINT=False,
    handleSIGTERM=False,
    handleSIGHUP=False
)