1、介绍
对应http请求对象。两种设置方法:
- 基于url设置
- 基于请求报文message设置,伴随设置协议类型https_flag
2、代码
import re
import time
import requests
from api.PropertiesClasses import Headers
from api.ResponseClass import Response
from api.UrlClass import Url
"""
http请求对象
"""
class Request:
def __init__(self, url: str = '', https_flag: bool = False, message: str = ''):
# 请求方法,默认是get
self.method = 'GET'
# 协议版本
self.protocol_version = 'HTTP/1.1'
# 请求头部,至少有host这个头部字段。
self.headers = Headers()
# 请求体部
self.body = ''
# url,主要是包含协议部分。
self.url = ''
# 编号,默认为-1,从1开始递增
self.id = -1
# 请求的发送时间,格式是20230423 10:00:00
self.send_time = ''
# 响应时延,float类型,单位是秒
self.wait_time = -1
# 响应对象
self.res = None
if url != "":
self.url = url
u = Url(url)
self.headers.update_or_add("Host", u.hostname + u.port)
elif message != "":
pattern = "^([\\S]*) ([\\S]*) ([\\S]*)((\n[^\n]+)*)\n\n(.*)"
result = re.findall(pattern=pattern, string=message, flags=re.DOTALL)
if result:
self.method = result[0][0]
self.protocol_version = result[0][2]
self.body = result[0][5]
if result[0][3] != "":
self.headers = Headers(result[0][3])
self.url = "https://" if https_flag else "http://"
self.url = self.url + str(self.headers.getFirstValue("Host")) + str(result[0][1])
def send(self, timeout: float = None, d: dict = None):
if type(timeout)==int and timeout <= 0:
timeout = None
# 记录发送请求的时间
t1 = time.time()
self.send_time = time.strftime("%Y%m%d-%H:%M:%S")
# 对请求头部处理
headers_dict = dict(self.headers.property_list)
if type(d) == dict:
headers_dict.update(d)
try:
resp = requests.request(method=self.method, url=self.url, headers=headers_dict, allow_redirects=False,
data=self.body, timeout=timeout)
# 实际使用的header进行再赋值
self.headers = Headers(resp.request.headers)
self.res = Response(resp)
# 计算等待的时间,整数和小数部分一共保留六位
self.wait_time = str(time.time() - t1)[:6]
except Exception as e:
print(e)
"""
获取报文
"""
def get_message(self):
"""get_message()->str"""
u = Url(self.url)
message = '%s %s %s\n%s\n\n%s' % (self.method, u.path + u.query, self.protocol_version,
self.headers.toString(), self.body)
return message
"""
克隆,不包括响应信息,以及id信息
"""
def clone(self):
"""clone() -> Request"""
c = Request()
c.method = self.method
c.protocol_version = self.protocol_version
c.url = self.url
c.headers = self.headers.clone()
c.body = self.body
return c
标签:url,self,Request,headers,api,result,import,message
From: https://www.cnblogs.com/wd404/p/17432339.html