python处理http请求以及遇到问题的解决(4)

# coding:utf-8
import urllib,httplib,os,logging,config,time,json,mysql
class RequestInterface(object):

# 判断接口地址HTTP状态是否200
def __http_code(self, url):  # __该方法被隐藏不能被py文件外的其他方法调用
    try:
        if url != '':
            r = requests.get(url)
            code = r.status_code
        else:
            code = '1000'  # 请求参数错误
    except Exception as error:  # 记录日志到log.txt文件
        code = '9999'  # http请求异常
        logging.basicConfig(filename=os.path.join(os.getcwd(), './log.txt'),
                            level=logging.DEBUG,
                            format='%(asctime)s %(filename)s[line:%(lineno)d] %(levekname)s %(message)s')
        logger = logging.getLogger(__name__)
        logger.exception(error)
    return code

# POST请求,参数在body中
def __http_post(self, interface_url, headerdata, param, environ):
    '''参数有:接口地址,头文件,接口入参,执行环境(测试,生产)'''
    try:
        if interface_url != '' and environ == u'test':
            http_client = httplib.HTTPConnection(config.envoron_test['ip'],
                          config.environ_test['port'], timeout=config.environ_test['timeout'])  # 创建HTTP连接
            http_client.request("POST", interface_url, body=param, headers=headerdata)
            response = http_client.getresponse()
            if response.status == 200:
                return response.read()
            else:
                return "2004"  # 接口返回状态错误
        elif interface_url != '' and environ == u'product':
            http_client = httplib.HTTPConnection(config.environ_product['ip'],
                        config.environ_product['port'], timeout=config.environ_product['timeout'])
            http_client.request("POST", interface_url, body=param, headers=headerdata)
            response = http_client.getresponse()
            if response.status == 200:
                return response.read()
            else:
                return "2004"  # 接口返回状态错误
        elif interface_url == '':
            return '2002'  # 接口地址参数为空
        elif self.__http_code(interface_url) != 200: ##调用同个类里的方法
            return '2003'  # 接口http访问错误
    except Exception as error:
        logging.basicConfig(filename=os.path.join(os.getcwd(), './log.txt'),
                            level=logging.DEBUG,
                            format='%(asctime)s %(filename)s[line:%(lineno)d] %(levekname)s %(message)s')
        logger = logging.getLogger(__name__)
        logger.exception(error)
        return '9999'  # http请求异常

# GET请求,参数在接口地址后面
def __http_get(self, interface_url, headerdata, param, environ):
    '''参数有:接口地址,头文件,接口入参,执行环境(测试,生产)'''
    try:
        if interface_url != '' and environ == u'test':
            requrl = interface_url + param
            http_client = httplib.HTTPConnection(config.environ_test['ip'],
                         config.environ_test['port'], timeout=config.environ_test['timeout'] )
            http_client.request(method="GET", url=requrl, body=None, headers=headerdata)
            response = http_client.getresponse()
            print(response)
            if response.status == 200:
                return response.read()
            else:
                return "3004"  # 接口返回状态错误
        elif interface_url != '' and environ == u'product':
            requrl = interface_url + param
            http_client = httplib.HTTPConnection(config.environ_product['ip'],
                                                     config.environ_product['port'],
                                                     timeout=config.environ_product['timeout'])
            http_client.request(method="GET", url=requrl, body=None, headers=headerdata)
            response = http_client.getresponse()
            print(response)
            if response.status == 200:
                return response.read()
            else:
                return "3004"  # 接口返回状态错误
        elif interface_url == '':
            return '3002'  # 接口地址参数为空

        elif self.__http_code(interface_url) != 200:
            return '3003'  # 接口http访问错误
    except Exception as error:
        logging.basicConfig(filename=os.path.join(os.getcwd(), './log.txt'),
                            level=logging.DEBUG,
                            format='%(asctime)s %(filename)s[line:%(lineno)d] %(levekname)s %(message)s')
        logger = logging.getLogger(__name__)
        logger.exception(error)
        return '9999'  # http请求异常

# 统一处理http请求
def http_request(self, interface_url, headerdata, param, type, environ=u'test', default_param=None):
    '''参数有:接口地址,头文件,接口入参,请求方式,执行环境(测试,生产,默认是测试),默认参数'''
    try:
        if type == 'get' or type == 'GET':
            result = self.__http_get(interface_url, headerdata, param, environ)
        elif type == 'post' or type == 'POST':
            result = self.__http_post(interface_url, headerdata, param, environ)
        else:
            result = "1000:请求参数错误"  # 请求参数类型错误
    except Exception as error:  # 记录日志到log.txt文件
        result = "9999"  # 系统异常返回码
        logging.basicConfig(filename=os.path.join(os.getcwd(), './log.txt'),
                            level=logging.DEBUG,
                            format='%(asctime)s %(filename)s[line:%(lineno)d] %(levekname)s %(message)s')
        logger = logging.getLogger(__name__)
        logger.exception(error)
    return result


if __name__ == "__main__":
    test_interface = RequestInterface()  # 实例化HTTP请求类
    test_db = mysql.Operationdb_interface()   # 实例化mysql处理类
    sen_sql =('select exe_mode,url_interface, header_interface, 
    params_interface from case_interface where id=1')
    interface_params = test_db.select_one(sen_sql)  # 获取数据
    interface_url = interface_params['url_interface']
    headerdata = json.loads(interface_params['header_interface'])
    param = interface_params['params_interface']
    type=interface_params['exe_mode']         ######之前缺失的一行代码
    result = test_interface.http_request(interface_url=interface_url,
                                     headerdata=headerdata,
                                     param=param, type=type,
                                     environ=u'test', default_param=None)
print(result)

出现过一下几个问题1

python处理http请求以及遇到问题的解决(4)_第1张图片
image.png

原因是在创建数据库连接,新建游标的代码里,少了返回数据类型的转换 然后加了一句
self.cur=self.conn.cursor(cursorclass = MySQLdb.cursors.DictCursor)
继续运行代码,然后又出现了问题,提示请求参数错误 最后发现缺少了倒数第六行的内容,加上运行就成功了

你可能感兴趣的:(python处理http请求以及遇到问题的解决(4))