Flask路由中使用Kaleido调用Plotly的pio.write_image导出图片时程序挂起
Flask路由中使用Kaleido调用Plotly的pio.write_image导出图片时程序挂起
我有一个Flask应用,需要展示图片,同时还要用pio.write_image将图片本地存储。在普通Python脚本(helperz.py)里测试这段逻辑是完全正常的:
if __name__ == "__main__": ic("name=main in strategies_helperz") print(plotly.__version__, kaleido.__version__) # create data data_original = generate_dummy_data(symbol="BTCUSDT", num_records=100) # transform to dataframe df = klines_to_dataframe(data_original) fig = plot_ohlc(df=df, exchange="mexc") user="ZEoJt367" src_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) current_time = datetime.now().strftime("%Y%m%d_%H%M%S") folder_path = os.path.join(src_path, "screenshots", user) if not os.path.exists(folder_path): ic(f'{folder_path} not existing, should create one!') os.makedirs(folder_path) fileName = os.path.join(folder_path, current_time + str(".png")) saveScreenshot(fig=fig, fileName=fileName, width=800, height=500)
下面是saveScreenshot函数的实现:
def saveScreenshot(fig, fileName, width=800, height=500): ic(f"def saveScreenshot to ${fileName}") try: pio.write_image(fig=fig, file=fileName, width=width, height=height, engine="kaleido") ic(f"image saved to ${fileName} !") return True except Exception as e: ic(f"Error saving image: {e}")
但如果在Flask的路由中使用这段逻辑(app.py文件,在文件层级上比helperz.py高一级),程序会直接挂起:
@app.route('/api/klines_for_plotly/<string:exchange>/<string:symbol>/<string:timeframe>', methods=['POST']) def apiKlinesForPlotly(exchange, symbol, timeframe): ic(f"def apiKlinesForPlotly - POST - for ${exchange}, symbol: ${symbol}, timeframe: ${timeframe}") klines_with_names=[] if exchange == "mexc": klines_mexc=getKlinesDataMexc(symbol=symbol, interval=timeframe) for data in klines_mexc: kline = Mexc_KLine(data) klines_with_names.append(kline) elif exchange == "binance": klines_binance=getKlinesDataBinance(symbol=symbol, interval=timeframe) for data in klines_binance: kline = Binance_KLine(data) klines_with_names.append(kline) # transforming klines_with_names to pandas df df=klinesWithNamesToDf(klines_with_names=klines_with_names) # creating a plotly fig based on df fig = plot_ohlc(df=df, exchange=exchange) user="ZEoJt367" src_path = os.path.dirname(os.path.abspath(__file__)) current_time = datetime.now().strftime("%Y%m%d_%H%M%S") folder_path = os.path.join(src_path, "screenshots", user) if not os.path.exists(folder_path): ic(f'{folder_path} not existing, should create one!') os.makedirs(folder_path) fileName = os.path.join(folder_path, current_time + str(".png")) fig = plot_ohlc(df=df, exchange=exchange) saveScreenshot(fig=fig, fileName=fileName, width=800, height=500) fig_json = fig.to_json() return fig_json
在这个场景下saveScreenshot永远不会执行完成。我已经按照很多类似问题的建议安装了旧版本的Kaleido,但还是没有解决问题。会不会是因为在Flask路由中使用时,这个函数需要改成异步的?
备注:内容来源于stack exchange,提问作者Gregor Soto拧ek
相关产品推荐
相关产品推荐

