requests 模块去访问登录Django web项目时因跨域问题登录不了,网上大部分解决方案是关闭Django内部的跨域配置,真是服了,这里我用的是请求端的解决方案。
跨域请求登录不成功主要配置有两个 1.header头中需要加Cookie:crsftoken=xxxxxxx
urlcsrf = "http://10.197.24.60:7100/users/user_login/"
result = requests.get(url=urlcsrf)
csrfcookie = requests.utils.dict_from_cookiejar(result.cookies)['csrftoken']
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36",
"cookie": "csrftoken=%s" % csrfcookie}
2.post请求中data需要加 csrfmiddlewaretoken 参数
soup = BeautifulSoup(result.content, "html.parser")
authenticity_token =soup.find('input',{'name':'csrfmiddlewaretoken'}).get("value")
data ={"username":"F455437","password":"dsfsdg123.","csrfmiddlewaretoken":authenticity_token}
r = requests.post(url=urlcsrf,data=data,headers=headers)
完整代码
import requests
if __name__ == '__main__':
urlcsrf = "http://10.197.24.60:7100/users/user_login/"
result = requests.get(url=urlcsrf)
csrfcookie = requests.utils.dict_from_cookiejar(result.cookies)['csrftoken']
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36",
"cookie": "csrftoken=%s" % csrfcookie}
soup = BeautifulSoup(result.content, "html.parser")
authenticity_token =soup.find('input',{'name':'csrfmiddlewaretoken'}).get("value")
data ={"username":"F1238775","password":"Whc159357.","csrfmiddlewaretoken":authenticity_token}
r = requests.post(url=urlcsrf,data=data,headers=headers)
print(r.status_code)
print(r.text)
返回状态200成功登录并打印
|