手柄请求.正文超时异常

2024-04-19 17:10:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用request.body将AJAX请求数据从jQuery获取到django应用程序,但有时request.body会导致Dyno超时,我想是因为用户断开连接,django一直在等待用户的请求,异常情况如下:

File "/app/myapp/views.py", line 271, in proccess_api
File "/app/.heroku/python/lib/python2.7/site-packages/django/http/request.py", line 233, in body
File "/app/.heroku/python/lib/python2.7/site-packages/django/http/request.py", line 292, in read
File "/app/.heroku/python/lib/python2.7/site-packages/django/core/handlers/wsgi.py", line 51, in read
File "/app/.heroku/python/lib/python2.7/site-packages/django/core/handlers/wsgi.py", line 45, in _read_limited
File "/app/.heroku/python/lib/python2.7/site-packages/newrelic-2.60.0.46/newrelic/api/web_transaction.py", line 780, in read
File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/http/body.py", line 212, in read
File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/http/body.py", line 128, in read
File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/http/unreader.py", line 38, in read
File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/http/unreader.py", line 65, in chunk
File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/workers/base.py", line 176, in handle_abort

流程中的行api:

^{pr2}$

我在Heroku上使用django1.8.11,例外是用newrelic记录的。在

我的问题是:

  • 如何处理此异常?在
  • 是否可以为request.body设置一个超时,以便请求不会阻止gunicorn worker?在

Tags: djangoinpyapphttpreadherokurequest
2条回答

我们没有太多你的信息,但是根据你发布的信息。。。在

“如何处理此异常?”req_data = json.loads(request.body)包装在try/except中,如下所示:

try:
    req_data = json.loads(request.body)
except:
    # Handle how you like
    # Maybe return a response 404 or 500?

如果您能告诉except要注意哪些特定的异常,那就更好了:

^{pr2}$

如果没有完整的错误输出(在File ...之后的所有内容)告诉我们Python到底抛出了什么错误,就很难说了。有关错误处理here的详细信息。在

“是否可以为request.body设置超时,以便请求不会阻止gunicorn worker?”

我想这不是超时问题。显然链接到该视图的URL得到了某种request,并试图读取它的body。根据您给我们的错误输出,request模块中的read抛出错误。这就是为什么你的代码停止了。request主体不可读这一事实意味着您应该像上面提到的那样将其包装在try/except中。在

另外,我的帮助是:req_data = json.loads(request.body.read())。在

看起来这是一个design limitation in gunicorn

Gunicorn is designed to be used behind a buffering reverse proxy

Gunicorn uses a pre-forking process model by default. This means that network requests are handed off to a pool of worker processes, and that these worker processes take care of reading and writing the entire HTTP request to the client. If the client has a fast network connection, the entire request/response cycle takes a fraction of a second. However, if the client is slow (or deliberately misbehaving), the request can take much longer to complete.

相关问题 更多 >