如何解决django csrf_token 验证与 python 请求模块
我想使用 python requests 模块发送 post 请求。因为,我使用 Django 作为后端服务器。所以,我需要为 post 方法验证 csrf_token。我知道我可以选择使用 Django 内置装饰器来停止 csrf_token 验证。但是,我不想为了跨站点保护而这样做。 我的 Django 示例代码:
from django.http import HttpResponse
from django.middleware.csrf import get_token
def pv(v,s):
print(f"----------Value of {s}-------")
print(f"Type= {type(v)}")
print()
print(v)
print()
def index(request):
pv(request.COOKIES,"HttpRequest.COOKIES")
pv(request.headers,"HttpRequest.headers")
token = get_token(request) # I think,Here have some worng. But What?
return HttpResponse("Hello World")
index() 适用于 get 和 post 请求。虽然我没有在示例代码中使用 redirect() 作为 post 方法。这是我使用 python requests 模块获取和发布请求代码:
import requests
import time
def pv(obj,s):
print(f"-----Value of {s} --------")
print(type(obj))
print(obj)
print()
url = "http://192.168.0.102:8000/home/"
data = {"a":"5","b":4}
d = requests.get(url)
time.sleep(2)
requests.post(url,cookies=d.cookies,data=data)
# For Test
pv(d.headers,"d.headers")
pv(d.cookies['csrftoken'],"d.cookies")
get 请求正常工作并返回我 csrf_token.when 我将此令牌与 post 方法一起使用。 Django 服务器给我 Forbidden(CSRF 令牌丢失或不正确。):/home/ 错误并且发布请求无法正常工作。如何验证 csrf_token?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。