flask.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. """
  2. Flask backend
  3. """
  4. import json
  5. import logging
  6. import threading
  7. from flask import Flask, request, send_from_directory, Response
  8. from .httpbased import HttpContext, HttpHandler, run_event_loop
  9. from .utils import make_applications, cdn_validation
  10. from ..utils import STATIC_PATH, iscoroutinefunction, isgeneratorfunction
  11. from ..utils import get_free_port
  12. logger = logging.getLogger(__name__)
  13. class FlaskHttpContext(HttpContext):
  14. backend_name = 'flask'
  15. def __init__(self):
  16. self.response = Response()
  17. self.request_data = request.get_data()
  18. def request_obj(self):
  19. """返回当前请求对象"""
  20. return request._get_current_object()
  21. def request_method(self):
  22. """返回当前请求的方法,大写"""
  23. return request.method
  24. def request_headers(self):
  25. """返回当前请求的header字典"""
  26. return request.headers
  27. def request_url_parameter(self, name, default=None):
  28. """返回当前请求的URL参数"""
  29. return request.args.get(name, default=default)
  30. def request_json(self):
  31. """返回当前请求的json反序列化后的内容,若请求数据不为json格式,返回None"""
  32. try:
  33. return json.loads(self.request_data)
  34. except Exception:
  35. return None
  36. def set_header(self, name, value):
  37. """为当前响应设置header"""
  38. self.response.headers[name] = value
  39. def set_status(self, status: int):
  40. """为当前响应设置http status"""
  41. self.response.status_code = status
  42. def set_content(self, content, json_type=False):
  43. """设置相应的内容
  44. :param content:
  45. :param bool json_type: content是否要序列化成json格式,并将 content-type 设置为application/json
  46. """
  47. # self.response.data accept str and bytes
  48. if json_type:
  49. self.set_header('content-type', 'application/json')
  50. self.response.data = json.dumps(content)
  51. else:
  52. self.response.data = content
  53. def get_response(self):
  54. """获取当前的响应对象,用于在私图函数中返回"""
  55. return self.response
  56. def get_client_ip(self):
  57. """获取用户的ip"""
  58. return request.remote_addr
  59. def webio_view(applications, cdn=True,
  60. session_expire_seconds=None,
  61. session_cleanup_interval=None,
  62. allowed_origins=None, check_origin=None):
  63. """Get the view function for running PyWebIO applications in Flask.
  64. The view communicates with the browser by HTTP protocol.
  65. :param list/dict/callable applications: PyWebIO application.
  66. :param bool/str cdn: Whether to load front-end static resources from CDN, the default is ``True``.
  67. Can also use a string to directly set the url of PyWebIO static resources.
  68. :param int session_expire_seconds: Session expiration time.
  69. :param int session_cleanup_interval: Session cleanup interval, in seconds.
  70. :param list allowed_origins: Allowed request source list.
  71. :param callable check_origin: The validation function for request source.
  72. The arguments of ``webio_view()`` have the same meaning as for :func:`pywebio.platform.flask.start_server`
  73. """
  74. cdn = cdn_validation(cdn, 'error')
  75. handler = HttpHandler(applications=applications, cdn=cdn,
  76. session_expire_seconds=session_expire_seconds,
  77. session_cleanup_interval=session_cleanup_interval,
  78. allowed_origins=allowed_origins, check_origin=check_origin)
  79. def view_func():
  80. context = FlaskHttpContext()
  81. return handler.handle_request(context)
  82. view_func.__name__ = 'webio_view'
  83. return view_func
  84. def start_server(applications, port=8080, host='localhost', cdn=True,
  85. allowed_origins=None, check_origin=None,
  86. session_expire_seconds=None,
  87. session_cleanup_interval=None,
  88. debug=False, **flask_options):
  89. """Start a Flask server to provide the PyWebIO application as a web service.
  90. :param list/dict/callable applications: PyWebIO application.
  91. The argument has the same meaning and format as for :func:`pywebio.platform.tornado.start_server`
  92. :param int port: The port the server listens on.
  93. When set to ``0``, the server will automatically select a available port.
  94. :param str host: The host the server listens on. ``host`` may be either an IP address or hostname. If it’s a hostname, the server will listen on all IP addresses associated with the name. ``host`` may be an empty string or None to listen on all available interfaces.
  95. :param bool/str cdn: Whether to load front-end static resources from CDN, the default is ``True``.
  96. Can also use a string to directly set the url of PyWebIO static resources.
  97. :param list allowed_origins: Allowed request source list.
  98. The argument has the same meaning as for :func:`pywebio.platform.tornado.start_server`
  99. :param callable check_origin: The validation function for request source.
  100. The argument has the same meaning and format as for :func:`pywebio.platform.tornado.start_server`
  101. :param int session_expire_seconds: Session expiration time.
  102. If no client message is received within ``session_expire_seconds``, the session will be considered expired.
  103. :param int session_cleanup_interval: Session cleanup interval, in seconds.
  104. The server will periodically clean up expired sessions and release the resources occupied by the sessions.
  105. :param bool debug: Flask debug mode.
  106. If enabled, the server will automatically reload for code changes.
  107. :param flask_options: Additional keyword arguments passed to the ``flask.Flask.run``.
  108. For details, please refer: https://flask.palletsprojects.com/en/1.1.x/api/#flask.Flask.run
  109. """
  110. if not host:
  111. host = '0.0.0.0'
  112. if port == 0:
  113. port = get_free_port()
  114. cdn = cdn_validation(cdn, 'warn')
  115. app = Flask(__name__)
  116. app.add_url_rule('/', 'webio_view', webio_view(
  117. applications=applications, cdn=cdn,
  118. session_expire_seconds=session_expire_seconds,
  119. session_cleanup_interval=session_cleanup_interval,
  120. allowed_origins=allowed_origins,
  121. check_origin=check_origin
  122. ), methods=['GET', 'POST', 'OPTIONS'])
  123. @app.route('/<path:static_file>')
  124. def serve_static_file(static_file):
  125. return send_from_directory(STATIC_PATH, static_file)
  126. has_coro_target = any(iscoroutinefunction(target) or isgeneratorfunction(target) for
  127. target in make_applications(applications).values())
  128. if has_coro_target:
  129. threading.Thread(target=run_event_loop, daemon=True).start()
  130. if not debug:
  131. logging.getLogger('werkzeug').setLevel(logging.WARNING)
  132. app.run(host=host, port=port, debug=debug, **flask_options)