zoukankan      html  css  js  c++  java
  • 使用requests模块进行封装,帮你如何处理restful类型的接口

    import requests
    import os
    import sys
    from Common.plugs.get_config import r_config
    from Common.plugs.get_log import Log
    
    BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
    
    if sys.platform == "win32":
        conf_path = os.path.join(BASE_DIR, 'Common/conf/env_config.ini').replace('/', '\')
    else:
        conf_path = os.path.join(BASE_DIR, 'Common/conf/env_config.ini')
    
    log_path = r_config(conf_path, "log", "log_path")
    
    logger = Log(log_path)
    
    
    class BaseRequest:
    
        def __init__(self, method, url, data=None, cookies=None, headers=None):
            logger.info("准备发送 {0} 请求".format(method.upper()))
            logger.info("请求头: {0}".format(headers))
            logger.info("接口地址: {0}".format(url))
            logger.info("接口类型: {0}".format(method.upper()))
            logger.info("接口数据: {0}".format(data))
            try:
                if method.upper() == 'GET':
                    self.response = requests.get(url=url, params=data, cookies=cookies, headers=headers)
                    logger.info("完成 GET 请求")
                elif method.upper() == 'POST':
                    self.response = requests.post(url=url, data=data, cookies=cookies, headers=headers)
                    logger.info("完成 POST 请求")
                elif method.upper() == 'DELETE':
                    self.response = requests.delete(url=url, data=data, cookies=cookies, headers=headers)
                    logger.info("完成 DELETE 请求")
            except Exception as e:
                logger.error("请求报错:{0}".format(str(e)))
                raise e
    
        def get_status_code(self):
            logger.info("响应结果状态码:{0}".format(self.response.json()))
            return self.response.status_code
    
        def get_text(self):
            logger.info("响应结text:{0}".format(self.response.json()))
            return self.response.text
    
        def get_json(self):
            logger.info("响应结果json:{0}".format(self.response.json()))
            return self.response.json()
    
        def get_cookies(self):
            logger.info("响应结果cookie:{0}".format(self.response.json()))
            return self.response.cookies
    
    
    if __name__ == '__main__':
        cookies = None
        headers = {'User-Agent': 'Mozilla/5.0'}
        url = 'http://127.0.0.1:8888/api/private/v1/login'
    
        data = {'username': 'admin', 'password': '123456'}
    
        ret = BaseRequest('post', url=url, data=data, cookies=cookies, headers=headers)
        print(ret.get_json())
  • 相关阅读:
    自动化运维工具——ansible剧本playbook(三)
    自动化运维工具——ansible系列命令
    自动化运维工具——ansible命令使用(二)
    自动化运维工具——ansible安装入门(一)
    SSH密钥验证
    es中的或加should
    es聚合后比较结果显示
    es聚合having count>0
    类的内部调用和多线程调用解决事务、aop失效的问题
    es注意点
  • 原文地址:https://www.cnblogs.com/hghua/p/13149386.html
Copyright © 2011-2022 走看看