flask.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  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. from .utils import make_applications
  14. logger = logging.getLogger(__name__)
  15. class FlaskHttpContext(HttpContext):
  16. backend_name = 'flask'
  17. def __init__(self):
  18. self.response = Response()
  19. self.request_data = request.get_data()
  20. def request_obj(self):
  21. """返回当前请求对象"""
  22. return request._get_current_object()
  23. def request_method(self):
  24. """返回当前请求的方法,大写"""
  25. return request.method
  26. def request_headers(self):
  27. """返回当前请求的header字典"""
  28. return request.headers
  29. def request_url_parameter(self, name, default=None):
  30. """返回当前请求的URL参数"""
  31. return request.args.get(name, default=default)
  32. def request_json(self):
  33. """返回当前请求的json反序列化后的内容,若请求数据不为json格式,返回None"""
  34. try:
  35. return json.loads(self.request_data)
  36. except Exception:
  37. return None
  38. def set_header(self, name, value):
  39. """为当前响应设置header"""
  40. self.response.headers[name] = value
  41. def set_status(self, status: int):
  42. """为当前响应设置http status"""
  43. self.response.status_code = status
  44. def set_content(self, content, json_type=False):
  45. """设置相应的内容
  46. :param content:
  47. :param bool json_type: content是否要序列化成json格式,并将 content-type 设置为application/json
  48. """
  49. if json_type:
  50. self.set_header('content-type', 'application/json')
  51. self.response.data = json.dumps(content)
  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(applications,
  61. session_expire_seconds=None,
  62. session_cleanup_interval=None,
  63. allowed_origins=None, check_origin=None):
  64. """获取在Flask中运行PyWebIO任务的视图函数。基于http请求与前端进行通讯
  65. :param list/dict/callable applications: PyWebIO应用. 可以是任务函数或者任务函数的字典或列表。
  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. handler = HttpHandler(applications=applications,
  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(applications, 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 list/dict/callable applications: PyWebIO应用. 可以是任务函数或者任务函数的字典或列表。
  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. applications=applications,
  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. has_coro_target = any(iscoroutinefunction(target) or isgeneratorfunction(target) for
  130. target in make_applications(applications).values())
  131. if not disable_asyncio and has_coro_target:
  132. threading.Thread(target=run_event_loop, daemon=True).start()
  133. if not debug:
  134. logging.getLogger('werkzeug').setLevel(logging.WARNING)
  135. app.run(host=host, port=port, debug=debug, **flask_options)