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

标签 python django http-status-code-403 http-post

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

相关文章:

包含十六进制的字符串中的 python2 与 python3

python - Opencv imshow 不创建窗口

Python 获取设备名称

google-apps-script - 使用 UrlFetchApp 从 https ://discord. com 寻址端点时出现错误 (403)

python - 演示所有 PEP-8 规则的完整代码示例

django-two-factor-auth 无法访问管理站点

python - 验证用户帐户在 Django Rest Framework 中是否处于事件状态

javascript - 使用 XMLHttpRequest 提示文件下载

Php Curl 403 禁止错误