python开发封装(请求头封装)
程序员文章站
2023-11-13 14:08:40
import requests"""基于项目做定制化封装1、鉴权:token 2、项目通用的请求头:{"X-Lemonban-Media-Type": "lemonban.v2","Content-Type": "application/json"} 3、请求体格式:application/json"""def __headle_headers(token=None): """ 处理请求头 加上项目中必带的请求头。如果有token,加上token值 :param....
import requests """ 基于项目做定制化封装 1、鉴权:token 2、项目通用的请求头:{"X-Lemonban-Media-Type": "lemonban.v2","Content-Type": "application/json"} 3、请求体格式:application/json """ def __headle_headers(token=None): """ 处理请求头 加上项目中必带的请求头。如果有token,加上token值 :param token: token值 :return: headers """ headers = {"X-Lemonban-Media-Type": "lemonban.v2","Content-Type": "application/json"} if token: headers["Authorization"] = "Bearer {}".format(token) return headers def send_request(method,url,data=None,token=None): """ :param method: 请求方法 :param url: 请求地址 :param data: 请求数据 :param token: 请求的token值 :return: """ # 得到请求头信息 headers = __headle_headers(token) # 根据请求头类型 调用请求方法 method = method.upper() if method == "GET": # 只判断了get、post两种请求方法 rep = requests.get(url,data,headers=headers) else: rep = requests.post(url,json=data,headers=headers) return rep if __name__ == '__main__': # 登录 login_url = "http://api.lemonban.com/futureloan/member/login" # 登录地址 login_data = {"mobile_phone": "18311783673", "pwd": "1234567890"} # 登录数据 req = send_request("post",login_url,login_data) token = req.json()["data"]["token_info"]["token"] # 获取token值 # 充值 recharge_url = "http://api.lemonban.com/futureloan//member/recharge" # 充值地址 recharge_data = {"member_id": "206896", "amount": 500} # 充值数据 request = send_request("post",recharge_url,recharge_data,token) req = request.json()["data"]["leave_amount"] print(req) # 打印充值后的金额
本文地址:https://blog.csdn.net/u013917094/article/details/107079240