MOOC(7)- case依赖、读取json配置文件进行多个接口请求-封装接口请求(2)

末鹿安然 提交于 2020-02-15 19:18:08

与1的区别在于加入了构造函数

# 封装接口请求
import requests
import json


class RunMain:

    def __init__(self, url, method, data=None):
        self.res = self.run_main(url, method, data)

    def send_get(self, url, para):
        res = requests.get(url, para)
        return res.json()

    def send_post(self, url, data):
        res = requests.post(url, data)
        r = res.json()
        return json.dumps(r, indent=2, sort_keys=True, ensure_ascii=False)

    def run_main(self, url, method, data=None):
        res = None
        if method.upper() == "GET":
            res = self.send_get(url, data)
        elif method.upper() == "POST":
            res = self.send_post(url, data)
        else:
            print("请输入正确的参数")
        return res


if __name__ == "__main__":
    url = "http://apis.juhe.cn/rubbish/search"
    data = {"key": "6d9cc6b16d6cf63caded401b99c7311e",
            "q": "奶茶",
            "type": 2}
    r = RunMain(url, "post", data)
    print(r.res)

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!