python_发送请求类

Posted xmb

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python_发送请求类相关的知识,希望对你有一定的参考价值。

一、发送请求类

import requests

class MyRequest:
    def __init__(self,url,method=get,data=None,headers=None,is_json=False):
        method = method.lower()
        self.url = url
        self.data = data
        self.headers = headers
        self.is_json = is_json
        if hasattr(self,method):
            getattr(self,method)()    #反射

    def get(self):
        try:
            req = requests.get(self.url,self.data,heasers=self.headers).json()
        except Exception as e:
            self.response = {error:接口请求出错%s%e}
        else:
            self.response = req

    def post(self):
        try:
            if self.is_json:
                req = requests.post(self.url, json=self.data, heasers=self.headers).json()
            else:
                req = requests.post(self.url, self.data, heasers=self.headers).json()
        except Exception as e:
            self.response = {error: 接口请求出错%s%e}
        else:
            self.response = req

if __name__ == __main__:
    import jsonpath
    login = MyRequest( http://127.0.0.1:5000/login,data={username:xmb,password:123456})
    result = jsonpath.jsonpath(login.response,$..session_id)
    if result:
        print(登录成功)
    else:
        print(登录失败)

 

以上是关于python_发送请求类的主要内容,如果未能解决你的问题,请参考以下文章

Python 向 Postman 请求代码片段

基于Python+Requests库封装发送接口请求的工具类Python+Requests库做接口自动化框架设计系列多测师

基于Python+Requests库封装发送接口请求的工具类Python+Requests库做接口自动化框架设计系列多测师

求教golang中http发送post请求gb2312编码的解决方案

如何将列表视图中的数据从一个片段发送到另一个片段

使用 rxJava 和改造多次调用另一个请求中的请求