python 我的分享片段

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 我的分享片段相关的知识,希望对你有一定的参考价值。

from restclient import GET, POST
import simplejson as json
import logging
import socket

logger = logging.getLogger('rs.utils.restclient')

class ConnectAPI(object):
    '''
    all the way of connection web and api server
    '''

    def __init__(self, host, port, user=None, passwd=None, method='get'):
        self.host = host
        self.port = port
        self.user = user
        self.passwd = passwd
        self.method = method
        self.timeout = 60
        self.data_params = {}
        self.header = {}
        client_ip = socket.gethostbyname(socket.gethostname())
        self.header['Client-IP'] = client_ip
        
    def set_timeout(self, timeout):
        if isinstance(timeout, (int, basestring)):
            try:
                timeout = int(timeout)
            except ValueError, e:
                logger.error("timeout set is error:%s, timeout:%s"%(e, timeout))
                timeout = None
            if timeout is not None:
                self.timeout = timeout
        else:
            logger.error("timeout set is error, timeout param type is invalid, must be int or base10 string")

    def set_header(self, header):
        if isinstance(header, dict):
            self.header.update(header)
        else:
            logger.error("header set is error, header param type is invalid, must be dict type")

    def set_method(self, method):
        if method in ['get', 'post', 'put', 'delete']:
            self.method = method
        else:
            logger.error("method set is error, method param type is invalid, must be rest request type")

    def call_by_httplib(self, url, header={}, data_params={}, method=None, timeout=None):
        logger.debug('call rest api from the server by httplib, url: %s'%url)
        if header:
            self.set_header(header)
        if timeout:
            self.set_timeout(timeout)
        if method:
            self.set_method(method)
        if not isinstance(data_params, dict):
            result = {'status': 'failure', 'content': {'error':'the data params must be dict type'}}
            return result
        url = "".join([":".join([self.host, self.port]), url])
        try:
            socket.setdefaulttimeout(self.timeout)
            if self.method == 'get':
                json_data = GET(url, params=data_params, headers=self.header, accept=["application/json"], async=False)
            elif self.method == 'post':
                self.header['Content-Type'] = "application/json"
                self.header['Content-Length'] = len(data_params)
                self.header['Connection'] = "Keep-Alive"
                if self.user and self.passwd:
                    credential = (self.user, self.passwd)
                else:
                    credential = tuple()
                json_data = POST(url, params=data_params, headers=self.header, accept= ["application/json"], 
                                credentials=credential, async=False)
            try:
                dictinfos = json.loads(json_data)
                if 'errorcode' in dictinfos:
                    status = 'failure'
                elif 'result' in dictinfos and dictinfos['result'] != 3000:
                    status = 'failure'
                else:
                    status = 'success'
                result = {'status': status, 'content': dictinfos}
            except ValueError, e:
                logger.error("parse the json format is error: %s" %e)
                result = {'status': 'failure', 'content': {'error':'parse the json format is error'}} 
        except Exception, e:
            import traceback
            traceback.print_exc()
            # print 'can not call the rest api, connect the server error: %s' % e
            logger.error('can not call the rest api, connect the server error: %s'%e)
            result = {'status': 'failure', 'content': {'error':'can not call the rest api, connect the server error'}}               
        return result

以上是关于python 我的分享片段的主要内容,如果未能解决你的问题,请参考以下文章

微信小程序代码片段

微信小程序代码片段分享

你如何在 python 中处理 graphql 查询和片段?

15种Python片段去优化你的数据科学管道

html addthis分享片段和prelim样式

html 社交分享片段(WP)