对并不总是有响应的视图禁用 Django CSRF
我有一个 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我知道你已经有了答案,而且内德确实是对的;
但除此之外:不仅 Django 真正期望视图返回响应,你的客户端也如此!这是一个 HTTP 错误,如果不返回某些内容(因此立即关闭连接),可能会浪费资源!
我认为 204 无内容或 304 未修改(请参阅:HTTP 状态代码)是在这种情况下使用适当的 http 代码;在 django 中:
或
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:
or
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?