对并不总是有响应的视图禁用 Django CSRF

发布于 2024-09-10 09:59:16 字数 705 浏览 5 评论 0原文

我有一个 Django 视图,它接收不需要 CSRF 令牌的 POST。因此我在视图上使用了 @csrf_exempt 装饰器。问题是,有时我不会从视图中发出响应(它是一个 Twitter 机器人,它会收到每条推文的 HTTP POST,而我不想响应每条推文)。当我不发出响应时,我收到以下错误:

Traceback (most recent call last):

 File "/home/adam/webapps/newman/lib/python2.5/django/core/handlers/base.py", line 100, in get_response
   response = callback(request, *callback_args, **callback_kwargs)

 File "/home/adam/webapps/newman/lib/python2.5/django/views/decorators/csrf.py", line 24, in wrapped_view
   resp.csrf_exempt = True

AttributeError: 'NoneType' object has no attribute 'csrf_exempt'

resp(我假设是响应)为 None,因为视图仅通过 return 退出。 如何避免此错误并且在 POST 中仍然不需要 CSRF 令牌。

谢谢!

I have a Django view that receives POSTs which do not need to have the CSRF token. Therefore I used the @csrf_exempt decorator on the view. The problem is that sometimes I do not issue a response from the view (it's a Twitter bot, it receives an HTTP POST for every tweet and I do not want to respond to every tweet). When I don't issue a response I get the following error:

Traceback (most recent call last):

 File "/home/adam/webapps/newman/lib/python2.5/django/core/handlers/base.py", line 100, in get_response
   response = callback(request, *callback_args, **callback_kwargs)

 File "/home/adam/webapps/newman/lib/python2.5/django/views/decorators/csrf.py", line 24, in wrapped_view
   resp.csrf_exempt = True

AttributeError: 'NoneType' object has no attribute 'csrf_exempt'

resp (which I assume is the response) is None because the view was exited with just return.
How can I avoid this error and still not require CSRF tokens in the POST.

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

丶情人眼里出诗心の 2024-09-17 09:59:16

我知道你已经有了答案,而且内德确实是对的;
但除此之外:不仅 Django 真正期望视图返回响应,你的客户端也如此!这是一个 HTTP 错误,如果不返回某些内容(因此立即关闭连接),可能会浪费资源!

我认为 204 无内容或 304 未修改(请参阅:HTTP 状态代码)是在这种情况下使用适当的 http 代码;在 django 中:

return HttpResponse(status=204)

from django.http import HttpResponseNotModified
return HttpResponseNotModified()

I know you already got your answer, and indeed Ned's right;
but in addition to that: not only Django really expects views to return a response, your client also! It's an HTTP error and likely a resource waste not to return something (and thus close the connection straight away)!

I would think that a 204 No Content or 304 Not modified (see: HTTP Status Codes) are the appropriate http codes to use in this situation; in django:

return HttpResponse(status=204)

or

from django.http import HttpResponseNotModified
return HttpResponseNotModified()
对岸观火 2024-09-17 09:59:16

Django 确实希望视图函数返回响应。也许您可以返回一个空响应而不是“无”?或者返回一个HTTP错误代码?

Django really expects view functions to return responses. Maybe you could return an empty response instead of None? Or return an HTTP error code?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文