谷歌建站多少钱,小型 网站 源码,个人空间地址怎么注册,做网站的协议我们在做自动化测试的时候#xff0c;大家都是希望自己写的代码越简洁越好#xff0c;代码重复量越少越好。那么#xff0c;我们可以考虑将request的请求类型#xff08;如#xff1a;Get、Post、Delect请求#xff09;都封装起来。这样#xff0c;我们在编写用例的时候…我们在做自动化测试的时候大家都是希望自己写的代码越简洁越好代码重复量越少越好。那么我们可以考虑将request的请求类型如Get、Post、Delect请求都封装起来。这样我们在编写用例的时候就可以直接进行请求了。
1. 源码分析
我们先来看一下Get、Post、Delect等请求的源码看一下它们都有什么特点。
1Get请求源码 def get(self, url, **kwargs):rSends a GET request. Returns :class:Response object.:param url: URL for the new :class:Request object.:param \*\*kwargs: Optional arguments that request takes.:rtype: requests.Responsekwargs.setdefault(allow_redirects, True)return self.request(GET, url, **kwargs) 2Post请求源码
def post(self, url, dataNone, jsonNone, **kwargs):rSends a POST request. Returns :class:Response object.:param url: URL for the new :class:Request object.:param data: (optional) Dictionary, list of tuples, bytes, or file-likeobject to send in the body of the :class:Request.:param json: (optional) json to send in the body of the :class:Request.:param \*\*kwargs: Optional arguments that request takes.:rtype: requests.Responsereturn self.request(POST, url, datadata, jsonjson, **kwargs) 3Delect请求源码 def delete(self, url, **kwargs):rSends a DELETE request. Returns :class:Response object.:param url: URL for the new :class:Request object.:param \*\*kwargs: Optional arguments that request takes.:rtype: requests.Responsereturn self.request(DELETE, url, **kwargs)
4分析结果
我们发现不管是Get请求、还是Post请求或者是Delect请求它们到最后返回的都是request函数。那么我们再去看一看request函数的源码。 def request(self, method, url,paramsNone, dataNone, headersNone, cookiesNone, filesNone,authNone, timeoutNone, allow_redirectsTrue, proxiesNone,hooksNone, streamNone, verifyNone, certNone, jsonNone):Constructs a :class:Request Request, prepares it and sends it.Returns :class:Response Response object.:param method: method for the new :class:Request object.:param url: URL for the new :class:Request object.:param params: (optional) Dictionary or bytes to be sent in the querystring for the :class:Request.:param data: (optional) Dictionary, list of tuples, bytes, or file-likeobject to send in the body of the :class:Request.:param json: (optional) json to send in the body of the:class:Request.:param headers: (optional) Dictionary of HTTP Headers to send with the:class:Request.:param cookies: (optional) Dict or CookieJar object to send with the:class:Request.:param files: (optional) Dictionary of filename: file-like-objectsfor multipart encoding upload.:param auth: (optional) Auth tuple or callable to enableBasic/Digest/Custom HTTP Auth.:param timeout: (optional) How long to wait for the server to senddata before giving up, as a float, or a :ref:(connect timeout,read timeout) timeouts tuple.:type timeout: float or tuple:param allow_redirects: (optional) Set to True by default.:type allow_redirects: bool:param proxies: (optional) Dictionary mapping protocol or protocol andhostname to the URL of the proxy.:param stream: (optional) whether to immediately download the responsecontent. Defaults to False.:param verify: (optional) Either a boolean, in which case it controls whether we verifythe servers TLS certificate, or a string, in which case it must be a pathto a CA bundle to use. Defaults to True.:param cert: (optional) if String, path to ssl client cert file (.pem).If Tuple, (cert, key) pair.:rtype: requests.Response# Create the Request.req Request(methodmethod.upper(),urlurl,headersheaders,filesfiles,datadata or {},jsonjson,paramsparams or {},authauth,cookiescookies,hookshooks,)prep self.prepare_request(req)proxies proxies or {}settings self.merge_environment_settings(prep.url, proxies, stream, verify, cert)# Send the request.send_kwargs {timeout: timeout,allow_redirects: allow_redirects,}send_kwargs.update(settings)resp self.send(prep, **send_kwargs)return resp
从request源码可以看出它先创建一个Request然后将传过来的所有参数放在里面再接着调用self.send()并将Request传过去。这里我们将不在分析后面的send等方法的源码了有兴趣的同学可以自行了解。
分析完源码之后发现我们可以不需要单独在一个类中去定义Get、Post等其他方法然后在单独调用request。其实我们直接调用request即可。
2. requests请求封装
代码示例 import requestsclass RequestMain:def __init__(self):session管理器requests.session(): 维持会话,跨请求的时候保存参数# 实例化sessionself.session requests.session()def request_main(self, method, url, paramsNone, dataNone, jsonNone, headersNone, **kwargs)::param method: 请求方式:param url: 请求地址:param params: 字典或bytes作为参数增加到url中 :param data: data类型传参字典、字节序列或文件对象作为Request的内容:param json: json传参作为Request的内容:param headers: 请求头字典:param kwargs: 若还有其他的参数使用可变参数字典形式进行传递:return:# 对异常进行捕获try:封装request请求将请求方法、请求地址请求参数、请求头等信息入参。注 verify: True/False默认为True认证SSL证书开关cert: 本地SSL证书。如果不需要ssl认证可将这两个入参去掉re_data self.session.request(method, url, paramsparams, datadata, jsonjson, headersheaders, cert(client_crt, client_key), verifyFalse, **kwargs)# 异常处理 报错显示具体信息except Exception as e:# 打印异常print(请求失败{0}.format(e))# 返回响应结果return re_dataif __name__ __main__:# 请求地址url 请求地址# 请求参数payload {请求参数}# 请求头header {headers}# 实例化 RequestMain()re RequestMain()# 调用request_main并将参数传过去request_data re.request_main(请求方式, url, jsonpayload, headersheader)# 打印响应结果print(request_data.text) 注 如果你调的接口不需要SSL认证可将cert与verify两个参数去掉。
最后感谢每一个认真阅读我文章的人礼尚往来总是要有的虽然不是什么很值钱的东西如果你用得到的话可以直接拿走【文末领取】 【下面是我整理的2023年最全的软件测试工程师学习知识架构体系图全套资料】 一、Python编程入门到精通
二、接口自动化项目实战 三、Web自动化项目实战
四、App自动化项目实战 五、一线大厂简历
六、测试开发DevOps体系 七、常用自动化测试工具
八、JMeter性能测试 九、总结尾部小惊喜
生命不息奋斗不止。每一份努力都不会被辜负只要坚持不懈终究会有回报。珍惜时间追求梦想。不忘初心砥砺前行。你的未来由你掌握
生命短暂时间宝贵我们无法预知未来会发生什么但我们可以掌握当下。珍惜每一天努力奋斗让自己变得更加强大和优秀。坚定信念执着追求成功终将属于你
只有不断地挑战自己才能不断地超越自己。坚持追求梦想勇敢前行你就会发现奋斗的过程是如此美好而值得。相信自己你一定可以做到