码迷,mamicode.com
首页 > 编程语言 > 详细

python_发送请求类

时间:2019-11-30 20:56:21      阅读:81      评论:0      收藏:0      [点我收藏+]

标签:__init__   ons   method   lse   json   def   ==   false   code   

一、发送请求类

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_发送请求类

标签:__init__   ons   method   lse   json   def   ==   false   code   

原文地址:https://www.cnblogs.com/xumb/p/11963581.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!