Python接口自动化之requests请求封装!_python requests封装接口方法(1)

    try:
        result = requests.post(url, params=params, data=data, json=json)
        return result
    except Exception as e:
        print("post请求错误: %s" % e)
def run_main(self, method, **kwargs):
    """
    判断请求类型
    :param method: 请求接口类型
    :param kwargs: 选填参数
    :return: 接口返回内容
    """
    if method == 'get':
        result = self.get(**kwargs)
        return result
    elif method == 'post':
        result = self.post(**kwargs)
        return result
    else:
        print('请求接口类型错误')

if name == ‘main’:
# 以下是测试代码
# get请求接口
url = ‘https://api.apiopen.top/getJoke?page=1&count=2&type=video’
res = RequestHandler().get(url)
# post请求接口
url2 = ‘http://127.0.0.1:8000/user/login/’
payload = {
“username”: “vivi”,
“password”: “123456”
}
res2 = RequestHandler().post(url2,json=payload)
print(res.json())
print(res2.json())


请求结果如下:



{‘code’: 200, ‘message’: ‘成功!’, ‘result’: [{‘sid’: ‘31004305’, ‘text’: ‘羊:师傅,理个发,稍微修一下就行’, ‘type’: ‘video’, ‘thumbnail’: ‘http://wimg.spriteapp.cn/picture/2020/0410/5e8fbf227c7f3_wpd.jpg’, ‘video’: ‘http://uvideo.spriteapp.cn/video/2020/0410/5e8fbf227c7f3_wpd.mp4’, ‘images’: None, ‘up’: ‘95’, ‘down’: ‘1’, ‘forward’: ‘0’, ‘comment’: ‘25’, ‘uid’: ‘23189193’, ‘name’: ‘青川小舟’, ‘header’: ‘http://wimg.spriteapp.cn/profile/large/2019/12/24/5e01934bb01b5_mini.jpg’, ‘top_comments_content’: None, ‘top_comments_voiceuri’: None, ‘top_comments_uid’: None, ‘top_comments_name’: None, ‘top_comments_header’: None, ‘passtime’: ‘2020-04-12 01:43:02’}, {‘sid’: ‘30559863’, ‘text’: ‘机器人女友,除了不能生孩子,其他的啥都会,价格239000元’, ‘type’: ‘video’, ‘thumbnail’: ‘http://wimg.spriteapp.cn/picture/2020/0306/5e61a41172a1b_wpd.jpg’, ‘video’: ‘http://uvideo.spriteapp.cn/video/2020/0306/5e61a41172a1b_wpd.mp4’, ‘images’: None, ‘up’: ‘80’, ‘down’: ‘6’, ‘forward’: ‘3’, ‘comment’: ‘20’, ‘uid’: ‘23131273’, ‘name’: ‘水到渠成’, ‘header’: ‘http://wimg.spriteapp.cn/profile/large/2019/07/04/5d1d90349cd1a_mini.jpg’, ‘top_comments_content’: ‘为游戏做的秀’, ‘top_comments_voiceuri’: ‘’, ‘top_comments_uid’: ‘10250040’, ‘top_comments_name’: ‘不得姐用户’, ‘top_comments_header’: ‘http://wimg.spriteapp.cn/profile’, ‘passtime’: ‘2020-04-11 20:43:49’}]}
{‘token’: ‘eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxLCJ1c2VybmFtZSI6InZpdmkiLCJleHAiOjE1ODY4NTc0MzcsImVtYWlsIjoidml2aUBxcS5jb20ifQ.k6y0dAfNU2o9Hd9LFfxEk1HKgczlQfUaKE-imPfTsm4’, ‘user_id’: 1, ‘username’: ‘vivi’}


这样就完美了吗,no,no,no。以上代码痛点如下:


代码量大:只是封装了get、post请求,加上其他请求类型,代码量较大;


缺少会话管理:请求之间如何保持会话状态。



现在我也找了很多测试的朋友,做了一个分享技术的交流群,共享了很多我们收集的技术文档和视频教程。
如果你不想再体验自学时找不到资源,没人解答问题,坚持几天便放弃的感受
可以加入我们一起交流。而且还有很多在自动化,性能,安全,测试开发等等方面有一定建树的技术大牛
分享他们的经验,还会分享很多直播讲座和技术沙龙
可以免费学习!划重点!开源的!!!
qq群号:691998057【暗号:csdn999】



![](https://img-blog.csdnimg.cn/direct/80d7e70ae30e4d83a9c57c6834e2e753.png)


![](https://img-blog.csdnimg.cn/img_convert/fdc5a84d09ede23360e7ced15fa3abee.webp?x-oss-process=image/format,png)



我们再来回顾下get、post等请求源码,看下是否有啥特点。


get请求源码:




def get(url, params=None, **kwargs):
r""“Sends a GET request.
:param url: URL for the new :class:Request object.
:param params: (optional) Dictionary, list of tuples or bytes to send
in the query string for the :class:Request.
:param **kwargs: Optional arguments that request takes.
:return: :class:Response <Response> object
:rtype: requests.Response
“””
kwargs.setdefault(‘allow_redirects’, True)
return request(‘get’, url, params=params, **kwargs)


post请求源码:




def post(url, data=None, json=None, **kwargs):
r""“Sends a POST request.
:param url: URL for the new :class:Request object.
:param data: (optional) Dictionary, list of tuples, bytes, or file-like
object to send in the body of the :class:Request.
:param json: (optional) json data to send in the body of the :class:Request.
:param **kwargs: Optional arguments that request takes.
:return: :class:Response <Response> object
:rtype: requests.Response
“””
return request(‘post’, url, data=data, json=json, **kwargs)


仔细研究下,发现get、post请求返回的都是request函数。


既然这样,我们再来研究下request源码:




def request(method, url, **kwargs):
“”“Constructs and sends a :class:Request <Request>.
:param method: method for the new :class:Request object.
:param url: URL for the new :class:Request object.
:param params: (optional) Dictionary, list of tuples or bytes to send
in the query string for the :class:Request.
:param data: (optional) Dictionary, list of tuples, bytes, or file-like
object to send in the body of the :class:Request.
:param json: (optional) A JSON serializable Python object 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 'name': file-like-objects (or {'name': file-tuple}) for multipart encoding upload.
file-tuple can be a 2-tuple ('filename', fileobj), 3-tuple ('filename', fileobj, 'content_type')
or a 4-tuple ('filename', fileobj, 'content_type', custom_headers), where 'content-type' is a string
defining the content type of the given file and custom_headers a dict-like object containing additional headers
to add for the file.
:param auth: (optional) Auth tuple to enable Basic/Digest/Custom HTTP Auth.
:param timeout: (optional) How many seconds to wait for the server to send data
before giving up, as a float, or a :ref:(connect timeout, read timeout) <timeouts> tuple.
:type timeout: float or tuple
:param allow_redirects: (optional) Boolean. Enable/disable GET/OPTIONS/POST/PUT/PATCH/DELETE/HEAD redirection. Defaults to True.
:type allow_redirects: bool
:param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.
:param verify: (optional) Either a boolean, in which case it controls whether we verify
the server’s TLS certificate, or a string, in which case it must be a path
to a CA bundle to use. Defaults to True.
:param stream: (optional) if False, the response content will be immediately downloaded.
:param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, (‘cert’, ‘key’) pair.
:return: :class:Response <Response> object
:rtype: requests.Response
Usage::
>>> import requests
>>> req = requests.request(‘GET’, ‘https://httpbin.org/get’)
<Response [200]>
“””
# By using the ‘with’ statement we are sure the session is closed, thus we
# avoid leaving sockets open which can trigger a ResourceWarning in some
# cases, and look like a memory leak in others.
with sessions.Session() as session:
return session.request(method=method, url=url, **kwargs)

文末有福利领取哦~

👉一、Python所有方向的学习路线

Python所有方向的技术点做的整理,形成各个领域的知识点汇总,它的用处就在于,你可以按照上面的知识点去找对应的学习资源,保证自己学得较为全面。img

👉二、Python必备开发工具

img
👉三、Python视频合集

观看零基础学习视频,看视频学习是最快捷也是最有效果的方式,跟着视频中老师的思路,从基础到深入,还是很容易入门的。
img

👉 四、实战案例

光学理论是没用的,要学会跟着一起敲,要动手实操,才能将自己的所学运用到实际当中去,这时候可以搞点实战案例来学习。(文末领读者福利)
img

👉五、Python练习题

检查学习结果。
img

👉六、面试资料

我们学习Python必然是为了找到高薪的工作,下面这些面试题是来自阿里、腾讯、字节等一线互联网大厂最新的面试资料,并且有阿里大佬给出了权威的解答,刷完这一套面试资料相信大家都能找到满意的工作。
img

img

👉因篇幅有限,仅展示部分资料,这份完整版的Python全套学习资料已经上传

网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。

需要这份系统化学习资料的朋友,可以戳这里无偿获取

一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!

  • 7
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值