HandlerBase.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  1. import simplejson as json
  2. import traceback
  3. from concurrent.futures import ThreadPoolExecutor
  4. from tornado.web import RequestHandler
  5. from model.log import logger
  6. import time
  7. import base64
  8. import pandas as pd
  9. from model.DateUtils import DateUtils
  10. from pandas.io.excel import ExcelWriter
  11. from pandas import read_csv
  12. log = logger()
  13. class BaseHandler(RequestHandler, DateUtils):
  14. def __init__(self, application, request, **kwargs):
  15. RequestHandler.__init__(self, application, request, **kwargs)
  16. self._status_code = 200
  17. self.executor = ThreadPoolExecutor(200)
  18. self.set_default_headers()
  19. self._au = self.get_auth() if self.settings.get('auth') else True
  20. def options(self):
  21. # 返回方法1
  22. self.set_status(200)
  23. self.finish()
  24. def set_default_headers(self):
  25. super().set_default_headers()
  26. # 设置允许的请求头
  27. self.set_header("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS")
  28. self.set_header("X-XSS-Protecion", "1")
  29. self.set_header("Content-Security-Policy", "default-src 'self'")
  30. self.set_header("Access-Control-Allow-Credentials", "true")
  31. # 设置一些自己定义的请求头
  32. self.set_header("Access-Control-Allow-Headers",
  33. "Content-Type, Depth, User-Agent, Token, Origin, X-Requested-With, Accept, Authorization")
  34. self.set_header("Content-Type", "application/json; charset=UTF-8")
  35. self.set_header("Access-Control-Allow-Origin", "*")
  36. def write_json_tmp_java(self, data, status_code=200, msg='SUCCESS', total=1, total_data={}):
  37. self.write(json.dumps({'code': status_code, 'data': data, 'msg': msg}))
  38. def write_json(self, data, status_code=200, msg='success', total=1, total_data={}):
  39. self.write(json.dumps(
  40. {'status': {'msg': msg, "RetCode": status_code}, 'total': total, 'data': data, "total_data": total_data}))
  41. def write_fail(self, code=400, msg='error'):
  42. self.write(json.dumps({'status': {'msg': msg, "RetCode": code}}))
  43. def write_download(self, filename, data):
  44. self.set_header('Content-Type', 'application/octet-stream')
  45. self.set_header('Content-Disposition', f'attachment; filename={filename}.csv')
  46. self.set_header("Pargam", "no-cache")
  47. self.set_header("Cache-Control", "no-cache")
  48. df = pd.DataFrame(data).to_csv(encoding='utf-8')
  49. # print(df)
  50. # with open(f'./{pitcher}_{start}_{end}.csv','w',newline='') as f:
  51. # f.write(df)
  52. f = open(df)
  53. data = read_csv(f)
  54. data.to_excel('xxx.xlsx')
  55. self.write(data)
  56. def get_args(self):
  57. di = json.loads(self.request.body.decode(encoding='utf-8'))
  58. if isinstance(di, str):
  59. di = json.loads(di)
  60. return di
  61. def write_error(self, status_code, msg=None, **kwargs):
  62. if self.settings.get("serve_traceback") and "exc_info" in kwargs:
  63. # in debug mode, try to send a traceback
  64. lines = []
  65. for line in traceback.format_exception(*kwargs["exc_info"]):
  66. lines.append(line)
  67. self.write_json(dict(traceback=''.join(lines)), status_code, self._reason)
  68. elif msg:
  69. self.write_json(None, status_code, msg)
  70. else:
  71. self.write_json(None, status_code, self._reason)
  72. def _authentication(self):
  73. """
  74. :return: True, 认证通过, False 认证不通过
  75. """
  76. return True
  77. log.info("author %s" % self.request.headers)
  78. # log.info(self.request.remote_ip)
  79. if self.request.headers.get("Gip_real") == '183.129.168.74':
  80. return True
  81. if not self.request.headers.get("Authorization"):
  82. return False
  83. else:
  84. # redis 中判断值是否存在
  85. # ur = UserRedisComm()
  86. # key = "admin_account_check%s" % (self.request.headers.get("Authorization"))
  87. # return True if ur.r.get(key) else False
  88. return True
  89. def get_auth(self):
  90. # 不需要验证的请求
  91. authless = ['/api/get_yangguang_data', '/api/git_hook/data_center', '/api/git_hook/qc_web']
  92. url = self.request.full_url().split(str(self.settings.get('port')) + '/')[1]
  93. if url in authless:
  94. return True
  95. else:
  96. Authorization = self.request.headers.get('Authorization')
  97. if not Authorization:
  98. return False
  99. print(Authorization)
  100. try:
  101. origStr = Authorization.split(' ')[1][::-1]
  102. except:
  103. return False
  104. origStr += (4 - len(origStr) % 4) * "="
  105. print(origStr)
  106. print(float(base64.b64decode(origStr.encode('utf-8')).decode(encoding='utf-8', errors='ignore')))
  107. b = str(float(base64.b64decode(origStr.encode('utf-8')).decode(encoding='utf-8', errors='ignore')) * int(
  108. self.now.day))[:10]
  109. print("b:", b)
  110. diff = int(time.mktime(time.localtime())) - int(b)
  111. print(diff)
  112. if diff < 10:
  113. return True
  114. else:
  115. return False