我正在研究Flask并试图在Heroku上创建一个小网站。 在Heroku上部署时,我遇到了超时错误和长任务,并且可以通过超时增加来传递。经过更多调查,我发现另一种解决方案是流式传输。这篇文章与我的解决方案关系密切:https://librenepal.com/article/flask-and-heroku-timeout/ 但它不起作用。 30秒后仍然出现错误 文章中的代码:
from flask import Flask, Response
import requests
app = Flask(__name__)
def some_long_calculation(number):
'''
here will be some long calculation using this number
let's simulate that using sleep for now :)
'''
import time
time.sleep(5)
return number
@app.route('/')
def check():
def generate():
for i in range(10):
yield "<br/>" # notice that we are yielding something as soon as possible
yield str(some_long_calculation(i))
return Response(generate(), mimetype='text/html')
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8080, debug=True)
你对这个问题有什么看法吗?
答案 0 :(得分:0)
你无法在Heroku上的请求 - 响应周期中解决30秒的超时行为。这是通过Heroku路由网格强制执行的。
如果您需要制作这样长时间运行的请求,您可以选择以下几种方法:
答案 1 :(得分:0)
您可以通过使用流式响应来避免heroku的30秒限制,我刚刚确认它可以正常工作。
我在heroku中使用了带有gunicorn的烧瓶,除了链接的示例代码外,我需要做的其他事情是更改gunicorn超时设置:web:gunicorn“ app.app:create_app()” --timeout以我为例600默认超时为30秒,恰好与heroku的超时设置相同。