heroku上的Flask流式传输仍然会出现30秒超时错误

时间:2016-12-24 08:18:48

标签: python heroku flask

我正在研究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)

你对这个问题有什么看法吗?

2 个答案:

答案 0 :(得分:0)

你无法在Heroku上的请求 - 响应周期中解决30秒的超时行为。这是通过Heroku路由网格强制执行的。

如果您需要制作这样长时间运行的请求,您可以选择以下几种方法:

  1. 将大数据放入S3或其他文件存储服务的文件中。当人们发出请求时,向他们发送文件URL,然后让他们下载。 (这是最优的)
  2. 使用websockets。根据定义,Web套接字是永远不会在浏览器和服务器之间关闭的持久TCP连接。这非常适合需要连续第四次通信的应用,例如您所描述的内容。

答案 1 :(得分:0)

您可以通过使用流式响应来避免heroku的30秒限制,我刚刚确认它可以正常工作。

我在heroku中使用了带有gunicorn的烧瓶,除了链接的示例代码外,我需要做的其他事情是更改gunicorn超时设置:web:gunicorn“ app.app:create_app()” --timeout以我为例600默认超时为30秒,恰好与heroku的超时设置相同。

相关问题