HandlerBase.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132
  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. self.write(df)
  53. def get_args(self):
  54. di = json.loads(self.request.body.decode(encoding='utf-8'))
  55. if isinstance(di, str):
  56. di = json.loads(di)
  57. return di
  58. def write_error(self, status_code, msg=None, **kwargs):
  59. if self.settings.get("serve_traceback") and "exc_info" in kwargs:
  60. # in debug mode, try to send a traceback
  61. lines = []
  62. for line in traceback.format_exception(*kwargs["exc_info"]):
  63. lines.append(line)
  64. self.write_json(dict(traceback=''.join(lines)), status_code, self._reason)
  65. elif msg:
  66. self.write_json(None, status_code, msg)
  67. else:
  68. self.write_json(None, status_code, self._reason)
  69. def _authentication(self):
  70. """
  71. :return: True, 认证通过, False 认证不通过
  72. """
  73. return True
  74. log.info("author %s" % self.request.headers)
  75. # log.info(self.request.remote_ip)
  76. if self.request.headers.get("Gip_real") == '183.129.168.74':
  77. return True
  78. if not self.request.headers.get("Authorization"):
  79. return False
  80. else:
  81. # redis 中判断值是否存在
  82. # ur = UserRedisComm()
  83. # key = "admin_account_check%s" % (self.request.headers.get("Authorization"))
  84. # return True if ur.r.get(key) else False
  85. return True
  86. def get_auth(self):
  87. # 不需要验证的请求
  88. authless = ['/api/get_yangguang_data', '/api/git_hook/data_center', '/api/git_hook/qc_web']
  89. url = self.request.full_url().split(str(self.settings.get('port')) + '/')[1]
  90. if url in authless:
  91. return True
  92. else:
  93. Authorization = self.request.headers.get('Authorization')
  94. if not Authorization:
  95. return False
  96. print(Authorization)
  97. try:
  98. origStr = Authorization.split(' ')[1][::-1]
  99. except:
  100. return False
  101. origStr += (4 - len(origStr) % 4) * "="
  102. print(origStr)
  103. print(float(base64.b64decode(origStr.encode('utf-8')).decode(encoding='utf-8', errors='ignore')))
  104. b = str(float(base64.b64decode(origStr.encode('utf-8')).decode(encoding='utf-8', errors='ignore')) * int(
  105. self.now.day))[:10]
  106. print("b:", b)
  107. diff = int(time.mktime(time.localtime())) - int(b)
  108. print(diff)
  109. if diff < 10:
  110. return True
  111. else:
  112. return False