首页 > 编程语言 > 详细

python的api书写模板

时间:2019-10-15 14:38:34      阅读:88      评论:0      收藏:0      [点我收藏+]
import requests, json
import logging
from pyxis import settings
from .exceptions import HttpBadStatusException

logger = logging.getLogger(__name__)

class UserInfo():
    base_url = settings.USER_URL

    def __init__(self, user_id):
        self.user_id = user_id

    def getUserInfo(self):
        resp = requests.get(UserInfo.base_url)

        if resp.status_code == requests.codes.ok:
            if resp.content:
                try:
                    data = [x for x in json.loads(resp.text) if x[userId] == self.user_id][0]
                except json.JSONDecodeError: #处理json格式数据异常,json.JSONDecodeError是ValueError的一个子类
                    logger.error("resp.text is not json")
                logger.debug("url:{}\ndata: {}".format(resp.url, data))
            else:
                data = None
            return data
        else:
            logger.error("API access get bad status: {}\n"
                         "url: {}\n"
                         "response: {}".format(
                resp.status_code, resp.url, resp.text))
            raise HttpBadStatusException(get user info failed, resp)

excetptions文件:

class HttpBadStatusException(Exception):

    def __init__(self, msg, http_resp):
        super(HttpBadStatusException, self).__init__(msg)
        self.msg = msg
        self.http_resp = http_resp

    def __str__(self):
        output_msg = "{}\nurl: {}\nstatus_code: {}\nconent:{}".format(
            self.msg, self.http_resp.url, self.http_resp.status_code,
            self.http_resp.text
        )
        return  output_msg

 

python的api书写模板

原文:https://www.cnblogs.com/fxm1/p/11677142.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!