flask.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  1. """
  2. Flask backend
  3. .. note::
  4. 在 CoroutineBasedSession 会话中,若在协程任务函数内调用 asyncio 中的协程函数,需要使用 asyncio_coroutine
  5. """
  6. import json
  7. import logging
  8. import threading
  9. from flask import Flask, request, send_from_directory, Response
  10. from .httpbased import HttpContext, HttpHandler, run_event_loop
  11. from ..session import register_session_implement_for_target
  12. from ..utils import STATIC_PATH, iscoroutinefunction, isgeneratorfunction
  13. logger = logging.getLogger(__name__)
  14. class FlaskHttpContext(HttpContext):
  15. def __init__(self):
  16. self.response = Response()
  17. self.request_data = request.get_data()
  18. def request_method(self):
  19. """返回当前请求的方法,大写"""
  20. return request.method
  21. def request_headers(self):
  22. """返回当前请求的header字典"""
  23. return request.headers
  24. def request_url_parameter(self, name, default=None):
  25. """返回当前请求的URL参数"""
  26. return request.args.get(name, default=default)
  27. def request_json(self):
  28. """返回当前请求的json反序列化后的内容,若请求数据不为json格式,返回None"""
  29. try:
  30. return json.loads(self.request_data)
  31. except Exception:
  32. return None
  33. def set_header(self, name, value):
  34. """为当前响应设置header"""
  35. self.response.headers[name] = value
  36. def set_status(self, status: int):
  37. """为当前响应设置http status"""
  38. self.response.status_code = status
  39. def set_content(self, content, json_type=False):
  40. """设置相应的内容
  41. :param content:
  42. :param bool json_type: content是否要序列化成json格式,并将 content-type 设置为application/json
  43. """
  44. if json_type:
  45. self.set_header('content-type', 'application/json')
  46. self.response.data = json.dumps(content)
  47. else:
  48. self.response.data = content
  49. def get_response(self):
  50. """获取当前的响应对象,用于在私图函数中返回"""
  51. return self.response
  52. def webio_view(target,
  53. session_expire_seconds=None,
  54. session_cleanup_interval=None,
  55. allowed_origins=None, check_origin=None):
  56. """获取用于与后端实现进行整合的view函数,基于http请求与前端进行通讯
  57. :param target: 任务函数。任务函数为协程函数时,使用 :ref:`基于协程的会话实现 <coroutine_based_session>` ;任务函数为普通函数时,使用基于线程的会话实现。
  58. :param int session_expire_seconds: 会话不活跃过期时间。
  59. :param int session_cleanup_interval: 会话清理间隔。
  60. :param list allowed_origins: 除当前域名外,服务器还允许的请求的来源列表。
  61. 来源包含协议和域名和端口部分,允许使用 Unix shell 风格的匹配模式:
  62. - ``*`` 为通配符
  63. - ``?`` 匹配单个字符
  64. - ``[seq]`` 匹配seq内的字符
  65. - ``[!seq]`` 匹配不在seq内的字符
  66. 比如 ``https://*.example.com`` 、 ``*://*.example.com``
  67. :param callable check_origin: 请求来源检查函数。接收请求来源(包含协议和域名和端口部分)字符串,
  68. 返回 ``True/False`` 。若设置了 ``check_origin`` , ``allowed_origins`` 参数将被忽略
  69. :return: Flask视图函数
  70. """
  71. session_cls = register_session_implement_for_target(target)
  72. handler = HttpHandler(target=target, session_cls=session_cls,
  73. session_expire_seconds=session_expire_seconds,
  74. session_cleanup_interval=session_cleanup_interval,
  75. allowed_origins=allowed_origins, check_origin=check_origin)
  76. def view_func():
  77. context = FlaskHttpContext()
  78. return handler.handle_request(context)
  79. view_func.__name__ = 'webio_view'
  80. return view_func
  81. def start_server(target, port=8080, host='localhost',
  82. allowed_origins=None, check_origin=None,
  83. disable_asyncio=False,
  84. session_cleanup_interval=None,
  85. session_expire_seconds=None,
  86. debug=False, **flask_options):
  87. """启动一个 Flask server 来运行PyWebIO的 ``target`` 服务
  88. :param target: task function. It's a coroutine function is use CoroutineBasedSession or
  89. a simple function is use ThreadBasedSession.
  90. :param port: server bind port. set ``0`` to find a free port number to use
  91. :param host: server bind host. ``host`` may be either an IP address or hostname. If it's a hostname,
  92. :param list allowed_origins: 除当前域名外,服务器还允许的请求的来源列表。
  93. 来源包含协议和域名和端口部分,允许使用 Unix shell 风格的匹配模式:
  94. - ``*`` 为通配符
  95. - ``?`` 匹配单个字符
  96. - ``[seq]`` 匹配seq内的字符
  97. - ``[!seq]`` 匹配不在seq内的字符
  98. 比如 ``https://*.example.com`` 、 ``*://*.example.com``
  99. :param callable check_origin: 请求来源检查函数。接收请求来源(包含协议和域名和端口部分)字符串,
  100. 返回 ``True/False`` 。若设置了 ``check_origin`` , ``allowed_origins`` 参数将被忽略
  101. :param bool disable_asyncio: 禁用 asyncio 函数。仅在 ``target`` 为协程函数时有效。
  102. .. note:: 实现说明:
  103. 当使用Flask backend时,若要在PyWebIO的会话中使用 ``asyncio`` 标准库里的协程函数,则需要在单独开启一个线程来运行 ``asyncio`` 事件循环,
  104. 若程序中没有使用到 ``asyncio`` 中的异步函数,可以开启此选项来避免不必要的资源浪费
  105. :param int session_expire_seconds: 会话过期时间。若 session_expire_seconds 秒内没有收到客户端的请求,则认为会话过期。
  106. :param int session_cleanup_interval: 会话清理间隔。
  107. :param bool debug: Flask debug mode
  108. :param flask_options: Additional keyword arguments passed to the constructor of ``flask.Flask.run``.
  109. ref: https://flask.palletsprojects.com/en/1.1.x/api/?highlight=flask%20run#flask.Flask.run
  110. """
  111. app = Flask(__name__)
  112. app.add_url_rule('/io', 'webio_view', webio_view(
  113. target,
  114. session_expire_seconds=session_expire_seconds,
  115. session_cleanup_interval=session_cleanup_interval,
  116. allowed_origins=allowed_origins,
  117. check_origin=check_origin
  118. ), methods=['GET', 'POST', 'OPTIONS'])
  119. @app.route('/')
  120. @app.route('/<path:static_file>')
  121. def serve_static_file(static_file='index.html'):
  122. return send_from_directory(STATIC_PATH, static_file)
  123. if not disable_asyncio and (iscoroutinefunction(target) or isgeneratorfunction(target)):
  124. threading.Thread(target=run_event_loop, daemon=True).start()
  125. if not debug:
  126. logging.getLogger('werkzeug').setLevel(logging.WARNING)
  127. app.run(host=host, port=port, debug=debug, **flask_options)