md5加密
token鉴权------token关联操作-------cookie鉴权--------cookie关联操作
cookie的二次封装,联合校验
json和字典的区别和转化
https需要关闭警报,不使用SSL
login.py
# -*- coding: utf-8 -*-
# 2022/1/17
import hashlib
import requests
HOST = "http://121.41.14.39:8082"
def get_md5(psw):
#实例化一个md5对象
md5 = hashlib.md5()
#对元素进行加密
md5.update(psw.encode('utf-8'))
#返回加密对象
return md5.hexdigest()#16进制结果
class Login:
def login(self,indata,get_token=False):
url = f"{HOST}/account/sLogin"
indata["password"] = get_md5(indata["password"])
payload = indata
resp = requests.post(url, data=payload)
if get_token:
#token值从请求体中获取
#用户账号密码登录,数据库校验通过,返回token值,
#把token值写入缓存,后面接口关联操作从缓存使用token。
return resp.json()["data"]["token"]
else:
return resp.text
if __name__ == '__main__':
res = Login().login({"username":"th0004","password":"11449"}, get_token=False)
print(res)
shop.py
# -*- coding: utf-8 -*-
# 2022/1/17
"""
json'{"adb":"ADB"}',false,null,true
字典{'abd':'ADB'},False,None,True
字典转json,json.dump(dict)
json转字典,json.loads(json)
"""
import requests
from portday2.login import Login
import pprint
HOST = "http://121.41.14.39:8082"
class Shop:
def __init__(self, intoken):
# self.token = intoken
self.header = {"Authorization":intoken}
def shop_list(self, indata):
url = f"{HOST}/shopping/myShop"
payload = indata
#params,data都是表单,json是键值对格式
#get方法使用params较多,post方法使用data较多
resp = requests.get(url, params=payload, headers=self.header)
return resp
if __name__ == '__main__':
token = Login().login({"username":"th0004","password":"11449"}, get_token=True)
res = Shop(token).shop_list({"page":12,"limit":17})
print(res.json())#返回字典格式,把json转为字典格式
# print(res.content)#res.content是返回图片
# print(res.text)# res.text返回字符串格式
# print(res.raw)# res.raw返回原始格式
# pprint.pprint(res.json())
print(res.headers)
print(res.request.headers)
print(res.request.body)
cookies124.py
# -*- coding: utf-8 -*-
# 2022/1/17
"""
cookies的jsessionId存放在响应头的Set-Cookie内
cookie存放在浏览器内
cookie的二次封装
token存放在响应体内
token在服务器缓存里
"""
import requests
HOST = "http://120.55.190.222:7080"
HOST2 = "https://120.55.190.222/api/mgr/loginReq"
def login():
url = f"{HOST}/api/mgr/loginReq"
payload = {'username':'auto','password':'sdfsdfsdf'}
resp = requests.post(url, data=payload)
resp.headers#cookie值存放在响应头内
return resp.cookies#返回原生cookie值
def addlesson(inData, packing_twice=False):
url = f"{HOST}/api/mgr/sq_mgr/"
# 方案一:原生态的cookies
if packing_twice == False:
payload = inData # 此时 inData直接传入的是那个登录的原生态的cookies
else:
# 方案二:自己封装cookies 原有的cookies需要增加 "token":"123456"
#联合校验
payload = {"sessionid": inData, "token": "123456"}
resp = requests.post(url, cookies=payload)#参数必须是cookies
return resp
if __name__ == '__main__':
res = login()
# <RequestsCookieJar[<Cookie sessionid=o6of3lf33b23m5vsco6je0retqveisk0 for 120.55.190.222/>]>
res2 = res["sessionid"]
print(res2)
res3 = addlesson(res2,packing_twice=True)
print(res3.request.headers)
文章评论