utils.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. from functools import wraps
  4. import commands
  5. import time
  6. from flask import make_response, g, request
  7. from flask.wrappers import Response
  8. from werkzeug.utils import import_string, cached_property
  9. import jwt
  10. from models.initialize import *
  11. __author__ = 'James Iter'
  12. __date__ = '2017/03/01'
  13. __contact__ = 'james.iter.cn@gmail.com'
  14. __copyright__ = '(c) 2017 by James Iter.'
  15. class Utils(object):
  16. exit_flag = False
  17. thread_counter = 0
  18. @staticmethod
  19. def shell_cmd(cmd):
  20. try:
  21. exit_status, output = commands.getstatusoutput(cmd)
  22. return exit_status, str(output)
  23. except Exception as e:
  24. return -1, e.message
  25. @classmethod
  26. def signal_handle(cls, signum=0, frame=None):
  27. cls.exit_flag = True
  28. @staticmethod
  29. def dumps2response(func):
  30. """
  31. 视图装饰器
  32. http://dormousehole.readthedocs.org/en/latest/patterns/viewdecorators.html
  33. """
  34. @wraps(func)
  35. def _dumps2response(*args, **kwargs):
  36. ret = func(*args, **kwargs)
  37. if func.func_name != 'r_before_request' and ret is None:
  38. ret = dict()
  39. ret['state'] = ji.Common.exchange_state(20000)
  40. if isinstance(ret, dict) and 'state' in ret:
  41. response = make_response()
  42. response.data = json.dumps(ret, ensure_ascii=False)
  43. response.status_code = int(ret['state']['code'])
  44. if 'redirect' in ret and request.args.get('auto_redirect', 'True') == 'True':
  45. response.status_code = int(ret['redirect'].get('code', ret['state']['code']))
  46. response.headers['location'] = ret['redirect'].get('location', request.host_url)
  47. # 参考链接:
  48. # http://werkzeug.pocoo.org/docs/0.11/wrappers/#werkzeug.wrappers.BaseResponse.autocorrect_location_header
  49. # 变量操纵位置 werkzeug/wrappers.py
  50. response.autocorrect_location_header = False
  51. return response
  52. if isinstance(ret, Response):
  53. return ret
  54. return _dumps2response
  55. @staticmethod
  56. def superuser(func):
  57. @wraps(func)
  58. def _superuser(*args, **kwargs):
  59. if not g.superuser:
  60. ret = dict()
  61. ret['state'] = ji.Common.exchange_state(40301)
  62. return ret
  63. return func(*args, **kwargs)
  64. return _superuser
  65. @staticmethod
  66. def generate_token(uid):
  67. payload = {
  68. 'iat': ji.Common.ts(), # 创建于
  69. 'nbf': ji.Common.ts(), # 在此之前不可用
  70. 'exp': ji.Common.ts() + app.config['token_ttl'], # 过期时间
  71. 'uid': uid
  72. }
  73. return jwt.encode(payload=payload, key=app.config['jwt_secret'], algorithm=app.config['jwt_algorithm'])
  74. @staticmethod
  75. def verify_token(token):
  76. ret = dict()
  77. ret['state'] = ji.Common.exchange_state(20000)
  78. try:
  79. payload = jwt.decode(jwt=token, key=app.config['jwt_secret'], algorithms=app.config['jwt_algorithm'])
  80. return payload
  81. except jwt.InvalidTokenError, e:
  82. logger.error(e.message)
  83. ret['state'] = ji.Common.exchange_state(41208)
  84. raise ji.JITError(json.dumps(ret))
  85. class LazyView(object):
  86. """
  87. 惰性载入视图
  88. http://dormousehole.readthedocs.org/en/latest/patterns/lazyloading.html
  89. """
  90. def __init__(self, import_name):
  91. self.__module__, self.__name__ = import_name.rsplit('.', 1)
  92. self.import_name = import_name
  93. @cached_property
  94. def view(self):
  95. return import_string(self.import_name)
  96. def __call__(self, *args, **kwargs):
  97. return self.view(*args, **kwargs)
  98. def add_rule_api(blueprint, rule, api_func=None, **options):
  99. blueprint.add_url_rule(rule=rule, view_func=LazyView(''.join(['api.', api_func])), **options)
  100. def add_rule_views(blueprint, rule, views_func=None, **options):
  101. blueprint.add_url_rule(rule=rule, view_func=LazyView(''.join(['views.', views_func])), **options)
  102. @app.context_processor
  103. def utility_processor():
  104. def format_price(amount, currency=u'¥'):
  105. return u'{0:.2f}{1}'.format(amount, currency)
  106. def format_datetime_by_tus(tus, fmt='%y-%m-%d %H:%M'):
  107. return time.strftime(fmt, time.localtime(tus/1000/1000))
  108. def format_guest_status(status):
  109. from status import GuestState
  110. color = 'FF645B'
  111. icon = 'glyph-icon icon-bolt'
  112. desc = '未知状态'
  113. if status == GuestState.running.value:
  114. color = '00BB00'
  115. icon = 'glyph-icon icon-circle'
  116. desc = '运行中'
  117. elif status == GuestState.no_state.value:
  118. color = 'FFC543'
  119. icon = 'glyph-icon icon-spinner'
  120. desc = '创建中'
  121. elif status == GuestState.blocked.value:
  122. color = '3D4245'
  123. icon = 'glyph-icon icon-minus-square'
  124. desc = '被阻塞'
  125. elif status == GuestState.paused.value:
  126. color = 'B7B904'
  127. icon = 'glyph-icon icon-pause'
  128. desc = '暂停'
  129. elif status == GuestState.shutdown.value:
  130. color = '4E5356'
  131. icon = 'glyph-icon icon-terminal'
  132. desc = '关闭'
  133. elif status == GuestState.shutoff.value:
  134. color = 'FFC543'
  135. icon = 'glyph-icon icon-plug'
  136. desc = '断电'
  137. elif status == GuestState.crashed.value:
  138. color = '9E2927'
  139. icon = 'glyph-icon icon-question'
  140. desc = '已崩溃'
  141. elif status == GuestState.pm_suspended.value:
  142. color = 'FCFF07'
  143. icon = 'glyph-icon icon-anchor'
  144. desc = '悬挂'
  145. elif status == GuestState.migrating.value:
  146. color = '1CF5E7'
  147. icon = 'glyph-icon icon-space-shuttle'
  148. desc = '迁移中'
  149. elif status == GuestState.dirty.value:
  150. color = 'FCFF07'
  151. icon = 'glyph-icon icon-remove'
  152. desc = '创建失败,待清理'
  153. else:
  154. pass
  155. return '<span class="{icon}" style="color: #{color};">&nbsp;&nbsp;{desc}</span>'.format(
  156. icon=icon, color=color, desc=desc)
  157. return dict(format_price=format_price, format_datetime_by_tus=format_datetime_by_tus,
  158. format_guest_status=format_guest_status)