flask.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  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):
  44. """设置相应的内容
  45. :param content:
  46. :param bool json_type: content是否要序列化成json格式,并将 content-type 设置为application/json
  47. """
  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(target,
  60. session_expire_seconds=None,
  61. session_cleanup_interval=None,
  62. allowed_origins=None, check_origin=None):
  63. """获取在Flask中运行PyWebIO任务的视图函数。基于http请求与前端进行通讯
  64. :param target: 任务函数。任务函数为协程函数时,使用 :ref:`基于协程的会话实现 <coroutine_based_session>` ;任务函数为普通函数时,使用基于线程的会话实现。
  65. :param int session_expire_seconds: 会话不活跃过期时间。
  66. :param int session_cleanup_interval: 会话清理间隔。
  67. :param list allowed_origins: 除当前域名外,服务器还允许的请求的来源列表。
  68. 来源包含协议和域名和端口部分,允许使用 Unix shell 风格的匹配模式:
  69. - ``*`` 为通配符
  70. - ``?`` 匹配单个字符
  71. - ``[seq]`` 匹配seq内的字符
  72. - ``[!seq]`` 匹配不在seq内的字符
  73. 比如 ``https://*.example.com`` 、 ``*://*.example.com``
  74. :param callable check_origin: 请求来源检查函数。接收请求来源(包含协议和域名和端口部分)字符串,
  75. 返回 ``True/False`` 。若设置了 ``check_origin`` , ``allowed_origins`` 参数将被忽略
  76. :return: Flask视图函数
  77. """
  78. session_cls = register_session_implement_for_target(target)
  79. handler = HttpHandler(target=target, session_cls=session_cls,
  80. session_expire_seconds=session_expire_seconds,
  81. session_cleanup_interval=session_cleanup_interval,
  82. allowed_origins=allowed_origins, check_origin=check_origin)
  83. def view_func():
  84. context = FlaskHttpContext()
  85. return handler.handle_request(context)
  86. view_func.__name__ = 'webio_view'
  87. return view_func
  88. def start_server(target, port=8080, host='localhost',
  89. allowed_origins=None, check_origin=None,
  90. disable_asyncio=False,
  91. session_cleanup_interval=None,
  92. session_expire_seconds=None,
  93. debug=False, **flask_options):
  94. """启动一个 Flask server 将 ``target`` 任务函数作为Web服务提供。
  95. :param target: 任务函数。任务函数为协程函数时,使用 :ref:`基于协程的会话实现 <coroutine_based_session>` ;任务函数为普通函数时,使用基于线程的会话实现。
  96. :param int port: server bind port. set ``0`` to find a free port number to use
  97. :param str host: server bind host. ``host`` may be either an IP address or hostname. If it's a hostname,
  98. :param list allowed_origins: 除当前域名外,服务器还允许的请求的来源列表。
  99. 来源包含协议和域名和端口部分,允许使用 Unix shell 风格的匹配模式:
  100. - ``*`` 为通配符
  101. - ``?`` 匹配单个字符
  102. - ``[seq]`` 匹配seq内的字符
  103. - ``[!seq]`` 匹配不在seq内的字符
  104. 比如 ``https://*.example.com`` 、 ``*://*.example.com``
  105. :param callable check_origin: 请求来源检查函数。接收请求来源(包含协议和域名和端口部分)字符串,
  106. 返回 ``True/False`` 。若设置了 ``check_origin`` , ``allowed_origins`` 参数将被忽略
  107. :param bool disable_asyncio: 禁用 asyncio 函数。仅在 ``target`` 为协程函数时有效。
  108. .. note:: 实现说明:
  109. 当使用Flask backend时,若要在PyWebIO的会话中使用 ``asyncio`` 标准库里的协程函数,PyWebIO需要单独开启一个线程来运行 ``asyncio`` 事件循环,
  110. 若程序中没有使用到 ``asyncio`` 中的异步函数,可以开启此选项来避免不必要的资源浪费
  111. :param int session_expire_seconds: 会话过期时间。若 session_expire_seconds 秒内没有收到客户端的请求,则认为会话过期。
  112. :param int session_cleanup_interval: 会话清理间隔。
  113. :param bool debug: Flask debug mode
  114. :param flask_options: Additional keyword arguments passed to the constructor of ``flask.Flask.run``.
  115. ref: https://flask.palletsprojects.com/en/1.1.x/api/?highlight=flask%20run#flask.Flask.run
  116. """
  117. app = Flask(__name__)
  118. app.add_url_rule('/io', 'webio_view', webio_view(
  119. target,
  120. session_expire_seconds=session_expire_seconds,
  121. session_cleanup_interval=session_cleanup_interval,
  122. allowed_origins=allowed_origins,
  123. check_origin=check_origin
  124. ), methods=['GET', 'POST', 'OPTIONS'])
  125. @app.route('/')
  126. @app.route('/<path:static_file>')
  127. def serve_static_file(static_file='index.html'):
  128. return send_from_directory(STATIC_PATH, static_file)
  129. if not disable_asyncio and (iscoroutinefunction(target) or isgeneratorfunction(target)):
  130. threading.Thread(target=run_event_loop, daemon=True).start()
  131. if not debug:
  132. logging.getLogger('werkzeug').setLevel(logging.WARNING)
  133. app.run(host=host, port=port, debug=debug, **flask_options)