requests模块的讲解和应用
import requests import re from requests_toolbelt import MultipartEncoder from api.tools.handle_response import HandleResponse from api.tools.handle_attribute import HandleAttr from api.tools.handle_path import image_dir from api.conf.setting import image_info """ 核心功能: 兼容get、post、put各种请求类型,通过调用send_requests方法,进行统一实现 """ class HandleRequests: def __init__(self): self.header = {"Content-Type": "application/json;charset=UTF-8", "locale": "zh_CN"} self.handle_response = HandleResponse() # 请求头 def __handle_headers(self): # 判断是否需求鉴权,如果需要 if hasattr(HandleAttr, "access_token"): token = getattr(HandleAttr, "access_token") self.header["Authorization"] = "bearer{}".format(token) else: print("请求接口无需鉴权") # 图片上传接口 def __upload_image(self, method, url): """ ------WebKitFormBoundarybDRVSD8MmoICEAX9 Content-Disposition: form-data; name="file"; filename="Snipaste_2024-03-23_11-25-00.png" Content-Type: image/png ------WebKitFormBoundarybDRVSD8MmoICEAX9-- """ with open(file=image_dir, mode="rb") as image: # name图片名称和图片二进制,图片的格式 from_data = MultipartEncoder(fields={ "file": (image_info["file_name"], image, image_info["file_type"]) }) # 请求头处理(给header字典赋值)data.content_type 请求头格式value属性 self.header["Content-Type"] = from_data.content_type # post请求,表格形式传参 response = requests.request(url=url, method=method, data=from_data, headers=self.header) # 请求头处理完成后,重新赋值回来,图片接口请求头比较特殊,用完返回原有请求头 self.header["Content-Type"] = "application/json;charset=UTF-8" return response # 请求地址参数替换方法 def __replace_url(self, url: str): key_list = re.findall("#(\w.+?)#", url) # 如果key_list列表为非空,需要做参数替换 if len(key_list) > 0: for key in key_list: url = url.replace(f"#{key}#", str(getattr(HandleAttr, key))) print("替换后的请求地址:", url) return url else: print("无需进行请求地址参数替换") return url # 发送请求,兼容图片上传接口,处理请求头鉴权问题,请求url地址参数化问题 def send_requests(self, url, method, data, is_upload): # 鉴权获取请求头,处理鉴权问题 self.__handle_headers() # 请求地址url参数替换 new_url = self.__replace_url(url=url) if str(is_upload) == "1": # 图片上传请求 response = self.__upload_image(url=new_url, method=method) new_response = self.handle_response.handle_response(response=response) return new_response else: # 普通请求,是否需要鉴权 response = requests.request(url=new_url, method=method, json=data, headers=self.header) # 调用判断响应数据类型为字符串和json格式 new_response = self.handle_response.handle_response(response=response) return new_response if __name__ == '__main__': url = "http://mall.lemonban.com:8108/adminLogin" data = {'t': 1711704161096, 'principal': '', 'credentials': '', 'sessionUUID': '06697613-1183-4988-a9cf-64cbed1cce84', 'imageCode': ''} method = "post" cl = HandleRequests() response = cl.send_requests(url, method, data, is_upload="1") print(response) # response = cl.upload_image(url="http://shop.lemonban.com:8108/admin/file/upload/img",method="post") # print(response)