在FLASK中运行pypupeteer会产生ValueError:信号仅在主线程中有效

时间:2018-12-08 05:45:27

标签: python-3.x flask puppeteer google-chrome-headless pyppeteer

我正在尝试将pyppeteer集成到flask应用程序中。我有运行pyppeteer并获取页面截图的python脚本。如果我单独运行该脚本,则此文件为工作文件。

问题是在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.

以下代码用于捕获屏幕截图。

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

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

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

请建议我要去哪里了。

Python版本:3.7

1 个答案:

答案 0 :(得分:1)

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

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