python之编写HttpRequest工具类003

项目中常用的HTTP请求就是get、post请求,所以编写一个HTTP请求工具类:

import requests
import json

class HttpRequest:
    def http_request(self,method,url,header,data=None,cookie=None):#实例方法
        try:
            if method.upper()=="GET":#get请求
                res = requests.get(url=url,headers=header,data=data,cookies=cookie)
            elif method.upper()== "POST":#post请求
                res = requests.post(url=url,headers=header,data=data,cookies=cookie)
            else:
                print("请求方式不正确")
        except Exception as e:
            print("请求出错:{}".format(e))
            raise e
        return res #返回结果

当前文件中如何调用该工具类呢?必须实例化!

if __name__ == '__main__':
    header ={"User-Agent": "Chrome/75.0.3770.100","Content-Type": "application/json;charset=UTF-8"}
    login_url="http://xxx/futureloan/member/login"
    login_data={"mobile_phone": "18602510xx1", "pwd": "12345678"}
    login_res =HttpRequest().http_request("post",login_url,header,json.dumps(login_data))#实例化
    recharge_url="http://xxx/futureloan/member/recharge"
    recharge_data={"member_id": "1770205xx1", "amount": "10"}
    recharge_res = HttpRequest().http_request("post",recharge_url,header,json.dumps(recharge_data),login_res.cookies)#实例化
    print(recharge_res.text)

其他模块中如何引用呢?需要import一下!

from tools.http_request import HttpRequest #from 文件夹.模块名 import 类名

 

posted @ 2020-12-02 22:13  仰望浩瀚星辰  阅读(464)  评论(0编辑  收藏  举报