#!/usr/bin/env python # encoding: utf-8 """ * * ============================================================================ * * 版权所有 蜘蛛出行 * * * 网站地址: http://www.zhizhuchuxing.com * ---------------------------------------------------------------------------- * 这不是一个自由软件!您只能在不用于商业目的的前提下对程序代码进行修改和 * 使用;不允许对程序代码以任何形式任何目的的再发布。 * ============================================================================ * Author By: 倪宗锋 * FileName curl_interface.py * Create By 2017/12/12 13:53 $ """ import json import pycurl from io import * from urllib.parse import urlencode import time import logging from django.conf import settings import os class CurlInterface: __body = '' # 报文体 __type = 1 # 报文数据类型 1:json 2:xml 3 发送原数据接收xml 4 发送原数据 接收json 5:都是原数据 __response = '' # 返回值 __time_out = 200 # 超时时间 __url = '' # 接口地址 __verb = 'get' # 传值方式 __curl_get_info = '' # 校验概要 __log_msg = '' # 日志 __curl = '' # curl对象 __total_time = 0 # 总耗时 def __init__(self, body, type): """ 初始化curl类 :param body: 报文体 :param type: 报文数据类型 1:json 2:xml 3 发送原数据接收xml 4 发送原数据 接收json 5:都是原数据 """ self.__type = type self.__set_body(body) def __set_body(self, body): """ 设置报文体 :param body: :return: array|string """ if self.__type == 1: self.__body = json.dumps(body) elif self.__type == 2: self.__body = body elif self.__type == 3: self.__body = urlencode(body) elif self.__type == 4: self.__body = urlencode(body) else: self.__body = urlencode(body) def exec(self, url, verb): """ curl执行 :param url: 接口地址 :param verb: post|get 传值方式 :return: """ try: self.__verb = verb self.__url = url self.__curl = pycurl.Curl() b = BytesIO() self.__curl.setopt(pycurl.WRITEFUNCTION, b.write) self.__curl.setopt(pycurl.URL, url) # 路径 self.__curl.setopt(pycurl.ENCODING, 'gzip,deflate') # 编码格式 self.__curl.setopt(pycurl.FOLLOWLOCATION, 1) # self.__curl.setopt(pycurl.VERBOSE, 1) # 打印调试信息 # self.__curl.setopt(pycurl.HEADER, 1)#输出头部信息 self.__curl.setopt(pycurl.FOLLOWLOCATION, 1) self.__curl.setopt(pycurl.MAXREDIRS, 5) # 指定HTTP重定向的最大数 self.__curl.setopt(pycurl.DNS_CACHE_TIMEOUT, 60 * 60 * 24) # DNS解析缓存时间 不要调低 第一次可能时间很长 故需要长时间缓存dns解析 if self.__verb == 'POST': self.__curl.setopt(pycurl.POST, 1) self.__curl.setopt(pycurl.POSTFIELDS, self.__body) else: self.__curl.setopt(pycurl.HTTPGET, 1) self.__curl.perform() self.__response = b.getvalue().decode("utf-8") self.__total_time = self.__curl.getinfo(pycurl.TOTAL_TIME) b.close() self.__curl.close() return self.__set_return() except BaseException as e: return {'code': 1, 'msg': '接口返回异常', 'data': ''} def __set_return(self): """ 设置返回值 :return: """ if self.__type == 1: # 返回json result = json.loads(self.__response) elif self.__type == 2: # 返回xml result = self.__response elif self.__type == 3: # 返回xml result = self.__response elif self.__type == 4: # 返回json数据 result = json.loads(self.__response) else: # 返回原数据 result = self.__response res = result return res def __del__(self): """ 记录访问日志 :return: """ self.__log_msg = '' self.__log_msg += time.strftime('%Y-%m-%d %H:%I:%S', time.localtime(time.time())) + '\n' self.__log_msg += 'curl:' + self.__url + ' method:' + self.__verb + '\n' self.__log_msg += 'body:' + self.__body + '\n' self.__log_msg += 'response:' + self.__response + '\n\n' date = time.strftime('%Y-%m-%d', time.localtime(time.time())) log_file = settings.BASE_DIR + '/log/curl/' + date + '.log' # 日志路径 if os.path.exists(log_file) is False: # 日志文件不存在则创建 fobj = open(log_file, 'w') fobj.close() logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO) logging.info(self.__log_msg)