我的分享片段

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

rest_client.py
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
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号