通过os和requests对接口请求进行封装
作者:互联网
MyRequests.py
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
import requests
from common.MyConf import MyConf
import os
from common.my_path import Conf_dir
class MyRequests:
def __init__(self):
self.headers = {"****": "*****"} ---根据实际项目的请求头信息,以字典格式添加相应的字段数据
# 通过MyConf类读取ini格式的配置文件数据
env_conf = MyConf(os.path.join(Conf_dir,'Env_conf.ini')) ---Env_conf.ini用于存放项目环境配置的信息
self.base_url = env_conf.get('server','host')
# 拼接请求url
def __deal_url(self,api_url):
req_url = self.base_url + api_url
return req_url
# 处理包含token的请求头
def __deal_header(self,token=None):
# if token:
# self.headers["Authorization"] = "Bearer {}".format(token)
#
if token:
self.headers["Authorization"] = "Bearer {}".format(token)
# 封装请求的信息:方法、url、请求数据、登录令牌
def send_requests(self, method, api_url, data, token=None):
# 0.处理接口文档的url格式
url = self.__deal_url(api_url)
# 1. 添加请求头信息
self.__deal_header(token)
# 2.请求包含:请求方法-post or get ; 请求参数;请求url
# 3. post, json=***, get, data=***
if method.upper() == 'POST':
resp = requests.request(method,url,json=data,headers=self.headers)
else:
resp = requests.request(method,url,params=data,headers=self.headers)
return resp
标签:__,请求,url,对接口,headers,token,requests,os,self 来源: https://www.cnblogs.com/newhope-2020/p/15868163.html