# -*- coding: utf-8 -*-
# @Desc : 请求的封装
import json
import re
import requests
TOKEN = 'xxx-xxx-xxx-xxx'
class MyRequests:
def __init__(self, host, user_name=None, password=None):
"""
初始化
@param host: 登录地址
@param user_name: 登录名称
@param password: 登录密码
"""
self.host = host
if user_name and password:
token = self._login(user_name, password)
self.header = {'token': token}
else:
self.header = {'token': TOKEN}
self.header[
'User-Agent'] = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.87 Safari/537.36 SE 2.X MetaSr 1.0'
def _longin(self, user_name, password):
if user_name and password:
head = {'Content-Type': 'application/json'}
data = json.dumps({'username': user_name, 'password': password})
data = requests.post(self.host + 'login', data=data, headers=head, verify=False)
token = json.loads(data)['data']['token']
return token
def get_request(self, api_url='', params={}):
api_url, query_hash = self._request_data(api_url, params)
response = requests.get(api_url, params=query_hash)
return response
def post_request(self, api_url='', params={}):
api_url, query_hash = self._request_data(api_url, params)
response = requests.post(api_url, json=query_hash, headers=self.header, verify=False)
return response
def put_request(self, api_url='', params={}):
api_url, query_hash = self._request_data(api_url, params)
response = requests.put(api_url, json=query_hash, headers=self.header, verify=False)
return response
def delete_request(self, api_url='', params={}):
api_url, query_hash = self._request_data(api_url, params)
response = requests.delete(api_url, json=query_hash, headers=self.header, verify=False)
return response
def patch_request(self, api_url='', params={}):
api_url, query_hash = self._request_data(api_url, params)
response = requests.patch(api_url, json=query_hash, headers=self.header, verify=False)
return response
def _request_data(self, api_url='', params={}):
"""
数据处理
@param api_url:
@param params:
@return:
"""
url_params = re.findall(r'{(\w*)}', api_url)
api_url = api_url.format(**{k: v for k, v in params.items() if k in url_params})
api_url = '{}/{}'.format(self.host, api_url)
query_hash = {k: v for k, v in params.items() if k not in url_params}
return api_url, query_hash
my_request = MyRequests('192.156.1.66')
def all_request_entry(api_url='', method='', params={}):
"""所有请求入口"""
method = method.strip().lower()
method_func = method + '_request'
response = {}
if hasattr(my_request, method_func):
response = getattr(my_request, method_func)(api_url, params)
# 数据进行
return response
标签:封装,url,self,request,api,params,response,python3
From: https://www.cnblogs.com/ranxi/p/16758765.html