gpt4 book ai didi

python - Django 在发送 POST 请求时返回 403 错误

转载 作者:IT老高 更新时间:2023-10-28 21:50:49 27 4
gpt4 key购买 nike

当我使用以下 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com