一. 添加cookie
# ~ headers添加? ? ----headers = {'cookie': 'token=xxx;uid=1'}
res = requests.post(url='http://123.56.99.53:9001/api/uploadFile/',
headers={"Cookie": "uid=1;token=44c972f05d76fdd93c31f9c2b65bb098f308cdfc"
# ,"Content-Type": "multipart/form-data"},
files={"myfile1": open('D:\全力以富\文艺清新单页10.docx', 'rb')}
print(res.text)
# ~cookies 字典添加 ---cookies ={'cookies_are':'working'}/cookies = dict(cookies_are='working')
res = requests.post(url='http://123.56.99.53:9001/api/uploadFile/',
? ? ? ? ? ? ? cookies={"uid": "1", "token": "44c972f05d76fdd93c31f9c2b65bb098f308cdfc"},
? ? ? ? ? ? ? files={"myfile": open('D:\全力以富\文艺清新单页10.docx', 'rb')
? ? ? ? ? ? ? ? ? ? ?})
print(res.text)
res = requests.post(url='http://123.56.99.53:9001/api/get_salesMonthly/',
? ? ? ? ? ? ? ? ? ? headers={"Content-Type": "application/json"},
? ? ? ? ? ? ? ? ? ? json={"city": "110000", "month": "3"},
? ? ? ? ? ? ? ? ? ? cookies={"uid": "1", "token": "44c972f05d76fdd93c31f9c2b65bb098f308cdfc"})
print(res.text)
习题:cookies获取:先登录——再获取——给查询接口用 ----requests.get(url, cookies=cookies)
res1 = requests.post(url='http://123.56.99.53:9001/api/login/',
? ? ? ? ? ? ? ? ? ? headers={"Content-Type": "application/x-www-form-urlencoded"},
? ? ? ? ? ? ? ? ? ? data={"username": "admin", "password": "liulaoshi123"},
? ? ? ? ? ? ? ? ? ? allow_redirects=False)
#requests.utils.dict_from_cookiejar(res1.cookies)
# 从 cookie 对象中转字典可用来查看cookies
res2 = requests.post(url='http://123.56.99.53:9001/api/get_salesMonthly/',
? ? ? ? ? ? ? ? ? ? headers={"Content-Type": "application/json"},
? ? ? ? ? ? ? ? ? ? json={"city": "110000", "month": "3"},
? ? ? ? ? ? ? ? ? ? cookies=res1.cookies)
print(res2.text)
注: allow_redirects=False ----不允许自动重定向
二. 会话保持
1.创建一个session,保持登录
session = requests.session()
session.post(url='http://123.56.99.53:9001/api/login/',
headers={"Content-Type": "application/x-www-form-urlencoded"},
data={"username": "admin", "password": "liulaoshi123"})
res2 = session.post(url='http://123.56.99.53:9001/api/get_salesMonthly/',
headers={"Content-Type": "application/json"},
json={"city": "110000", "month": "3"})
print(res2.text)
注:session id不能放在url中暴露,session id需设置合理的退出和过期机制
三. 设置超时?timeout? ----requests.get(url=' ', timeout=1)
res = requests.get(url='http://www.google.com/',timeout=2)
print(res.staus_code)
注:如果超过几秒没有响应,则视为请求发送失败,?则抛出requests.exceptions.Timeout? ?timeout 仅对连接过程有效,与响应体的下载无关 ?? ??? ??? ??? ?
|