HandlerBase.py 4.9 KB

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