当我使用以下 Python 代码向我的 Django 网站发送 POST 请求时,我收到 403: Forbidden error。
url = 'http://www.sub.example.com/'
values = { 'var': 'test' }
try:
data = urllib.urlencode(values, doseq=True)
req = urllib2.Request(url, data)
response = urllib2.urlopen(req)
the_page = response.read()
except:
the_page = sys.exc_info()
raise
当我打开任何其他网站时,它可以正常工作。
example.com
也是 Django 网站,它也可以正常工作。
我想,这是 Django 配置问题,谁能告诉我应该怎么做才能提供对我的脚本的访问权限?
最佳答案
看这里https://docs.djangoproject.com/en/dev/ref/csrf/#how-to-use-it .
尝试使用 @csrf_exempt
标记您的 View 。这样,Django 的 CSRF 中间件将忽略 CSRF 保护。您还需要使用 from django.views.decorators.csrf import csrf_exempt
。见:https://docs.djangoproject.com/en/dev/ref/csrf/#utilities
请注意,通过在您的 View 上禁用 CSRF 保护,您打开了 CSRF 攻击的大门。
如果安全性对您至关重要,那么请考虑使用 @csrf_exempt
后跟 @requires_csrf_token
(请参阅:https://docs.djangoproject.com/en/dev/ref/csrf/#unprotected-view-needs-the-csrf-token)。然后,在你的脚本中传递这个 token ,就是这样。
关于python - Django 在发送 POST 请求时返回 403 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6800894/