util.py 文件源码

python
阅读 26 收藏 0 点赞 0 评论 0

项目:slackbot 作者: cybernetisk 项目源码 文件源码
def get_from_api(url, params=None, encoding=None, cache=False, cachename='dafault',
                 cache_experation=60):
    """
    Common method to get infomration from a REST api that doesn't use authentication
    :param url: URL for the api
    :param params: the parameter for the request
    :param encoding: to override the endogind
    :param cache: Use cache(default False
    :param cachename: Name of the cache
    :param cache_experation: when do you want the cache to expire in seconds, default : 60

    :return:
    """
    response = requests.get(url, params=params)
    if cache:
        requests_cache.install_cache(cachename, expire_after=cache_experation)
    if response.encoding is None:
        if encoding is None:
            response.encoding = chardet.detect(response.raw.data)['encoding']
        else:
            response.encoding = encoding
    if response.status_code is not 200:
        raise Exception('%s:%s' % (response.status_code, response.text))
    try:
        return json.loads(response.text)
    except Exception as e:
        raise Exception('Can\'t parse the json string\n %s' % url)
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号