Python造轮子-封装外部访问API

# 目录结构如下
- xxx_JDK
- - __init__.py
- - base.py
- - test.py
# __init__.py
is_pro = False
if is_pro:
    xxx_HOST_URL = '127.0.0.1:8080'
    URL_PREFIX = 'http://'
else:
    # 测试环境
    xxx_HOST_URL = '127.0.0.1:8081'
    URL_PREFIX = 'http://'
# base.py

import json
from urllib.parse import urljoin
from requests import Request, Session
from xxx_JDK import URL_PREFIX, xxx_HOST_URL


class ExtendAPIBase(object):
    """
     外部接口访问基础类
    """

    _APP_KEY = None
    _APP_SECRET = None
    _HOST_URL = '{}{}'.format(URL_PREFIX, xxx_HOST_URL)

    def __init__(self):
        pass

    def execute(self, uri, method, body=None):

        req = self.build_request(uri, method, body)
        prepped = req.prepare()
        s = Session()
        resp = s.send(prepped)
        resp = self.build_response(resp)
        return resp

    def build_request(self, uri, method, body):
        method = method.upper()
        url = urljoin(self._HOST_URL, uri)
        req = Request(method, url)

        if body:
            if req.method in ["POST", "PUT", "PATH"]:
                req.json = body
            else:
                req.params = body
        return req

    def build_response(self, resp):
        try:
            return resp.json()
        except (ValueError, json.JSONDecodeError) as e:
            raise resp.raise_for_status()

# test.py
from xxx_JDK.base import ExtendAPIBase


class xxxTest(ExtendAPIBase):

    def __init__(self):
        super(xxxTest, self).__init__()

    def test_api(self, request_param):
        """
        测试接口
        """
        return self.execute(
            '/api/v1/system/test/',
            'GET',
            request_param
        )

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

落笔成名

客官,辛苦则个

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值