You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

136 rivejä
4.9 KiB

  1. #!/usr/bin/env python
  2. # encoding: utf-8
  3. """
  4. *
  5. * ============================================================================
  6. * * 版权所有 蜘蛛出行 * *
  7. * 网站地址: http://www.zhizhuchuxing.com
  8. * ----------------------------------------------------------------------------
  9. * 这不是一个自由软件!您只能在不用于商业目的的前提下对程序代码进行修改和
  10. * 使用;不允许对程序代码以任何形式任何目的的再发布。
  11. * ============================================================================
  12. * Author By: 倪宗锋
  13. * FileName curl_interface.py
  14. * Create By 2017/12/12 13:53 $
  15. """
  16. import json
  17. import pycurl
  18. from io import *
  19. from urllib.parse import urlencode
  20. import time
  21. import logging
  22. from django.conf import settings
  23. import os
  24. class CurlInterface:
  25. __body = '' # 报文体
  26. __type = 1 # 报文数据类型 1:json 2:xml 3 发送原数据接收xml 4 发送原数据 接收json 5:都是原数据
  27. __response = '' # 返回值
  28. __time_out = 200 # 超时时间
  29. __url = '' # 接口地址
  30. __verb = 'get' # 传值方式
  31. __curl_get_info = '' # 校验概要
  32. __log_msg = '' # 日志
  33. __curl = '' # curl对象
  34. __total_time = 0 # 总耗时
  35. def __init__(self, body, type):
  36. """
  37. 初始化curl类
  38. :param body: 报文体
  39. :param type: 报文数据类型 1:json 2:xml 3 发送原数据接收xml 4 发送原数据 接收json 5:都是原数据
  40. """
  41. self.__type = type
  42. self.__set_body(body)
  43. def __set_body(self, body):
  44. """
  45. 设置报文体
  46. :param body:
  47. :return: array|string
  48. """
  49. if self.__type == 1:
  50. self.__body = json.dumps(body)
  51. elif self.__type == 2:
  52. self.__body = body
  53. elif self.__type == 3:
  54. self.__body = urlencode(body)
  55. elif self.__type == 4:
  56. self.__body = urlencode(body)
  57. else:
  58. self.__body = urlencode(body)
  59. def exec(self, url, verb):
  60. """
  61. curl执行
  62. :param url: 接口地址
  63. :param verb: post|get 传值方式
  64. :return:
  65. """
  66. try:
  67. self.__verb = verb
  68. self.__url = url
  69. self.__curl = pycurl.Curl()
  70. b = BytesIO()
  71. self.__curl.setopt(pycurl.WRITEFUNCTION, b.write)
  72. self.__curl.setopt(pycurl.URL, url) # 路径
  73. self.__curl.setopt(pycurl.ENCODING, 'gzip,deflate') # 编码格式
  74. self.__curl.setopt(pycurl.FOLLOWLOCATION, 1)
  75. # self.__curl.setopt(pycurl.VERBOSE, 1) # 打印调试信息
  76. # self.__curl.setopt(pycurl.HEADER, 1)#输出头部信息
  77. self.__curl.setopt(pycurl.FOLLOWLOCATION, 1)
  78. self.__curl.setopt(pycurl.MAXREDIRS, 5) # 指定HTTP重定向的最大数
  79. self.__curl.setopt(pycurl.DNS_CACHE_TIMEOUT, 60 * 60 * 24) # DNS解析缓存时间 不要调低 第一次可能时间很长 故需要长时间缓存dns解析
  80. if self.__verb == 'POST':
  81. self.__curl.setopt(pycurl.POST, 1)
  82. self.__curl.setopt(pycurl.POSTFIELDS, self.__body)
  83. else:
  84. self.__curl.setopt(pycurl.HTTPGET, 1)
  85. self.__curl.perform()
  86. self.__response = b.getvalue().decode("utf-8")
  87. self.__total_time = self.__curl.getinfo(pycurl.TOTAL_TIME)
  88. b.close()
  89. self.__curl.close()
  90. return self.__set_return()
  91. except BaseException as e:
  92. return {'code': 1, 'msg': '接口返回异常', 'data': ''}
  93. def __set_return(self):
  94. """
  95. 设置返回值
  96. :return:
  97. """
  98. if self.__type == 1: # 返回json
  99. result = json.loads(self.__response)
  100. elif self.__type == 2: # 返回xml
  101. result = self.__response
  102. elif self.__type == 3: # 返回xml
  103. result = self.__response
  104. elif self.__type == 4: # 返回json数据
  105. result = json.loads(self.__response)
  106. else: # 返回原数据
  107. result = self.__response
  108. res = result
  109. return res
  110. def __del__(self):
  111. """
  112. 记录访问日志
  113. :return:
  114. """
  115. self.__log_msg = ''
  116. self.__log_msg += time.strftime('%Y-%m-%d %H:%I:%S', time.localtime(time.time())) + '\n'
  117. self.__log_msg += 'curl:' + self.__url + ' method:' + self.__verb + '\n'
  118. self.__log_msg += 'body:' + self.__body + '\n'
  119. self.__log_msg += 'response:' + self.__response + '\n\n'
  120. date = time.strftime('%Y-%m-%d', time.localtime(time.time()))
  121. log_file = settings.BASE_DIR + '/log/curl/' + date + '.log' # 日志路径
  122. if os.path.exists(log_file) is False: # 日志文件不存在则创建
  123. fobj = open(log_file, 'w')
  124. fobj.close()
  125. logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO)
  126. logging.info(self.__log_msg)