flask.py 7.3 KB

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