flask.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  1. """
  2. Flask backend
  3. .. note::
  4. 在 AsyncBasedSession 会话中,若在协程任务函数内调用 asyncio 中的协程函数,需要使用 asyncio_coroutine
  5. .. attention::
  6. PyWebIO 的会话状态保存在进程内,所以不支持多进程部署的Flask。
  7. 比如使用 ``uWSGI`` 部署Flask,并使用 ``--processes n`` 选项设置了多进程;
  8. 或者使用 ``nginx`` 等反向代理将流量负载到多个 Flask 副本上。
  9. A note on run Flask with uWSGI:
  10. If you start uWSGI without threads, the Python GIL will not be enabled,
  11. so threads generated by your application will never run. `uWSGI doc <https://uwsgi-docs.readthedocs.io/en/latest/WSGIquickstart.html#a-note-on-python-threads>`_
  12. 在Flask backend中,PyWebIO使用单独一个线程来运行事件循环。如果程序中没有使用到asyncio中的协程函数,
  13. 可以在 start_flask_server 参数中设置 ``disable_asyncio=False`` 来关闭对asyncio协程函数的支持。
  14. 如果您需要使用asyncio协程函数,那么需要在在uWSGI中使用 ``--enable-thread`` 选项开启线程支持。
  15. """
  16. import asyncio
  17. import threading
  18. import time
  19. from functools import partial
  20. from typing import Dict
  21. from flask import Flask, request, jsonify, send_from_directory
  22. from ..session import CoroutineBasedSession, get_session_implement, AbstractSession, \
  23. set_session_implement, get_session_implement_for_target
  24. from ..utils import STATIC_PATH
  25. from ..utils import random_str, LRUDict
  26. # todo: use lock to avoid thread race condition
  27. _webio_sessions: Dict[str, AbstractSession] = {} # WebIOSessionID -> WebIOSession()
  28. _webio_expire = LRUDict() # WebIOSessionID -> last active timestamp
  29. DEFAULT_SESSION_EXPIRE_SECONDS = 60 * 60 * 4 # 超过4个小时会话不活跃则视为会话过期
  30. REMOVE_EXPIRED_SESSIONS_INTERVAL = 120 # 清理过期会话间隔(秒)
  31. WAIT_MS_ON_POST = 100 # 在处理完POST请求时,等待WAIT_MS_ON_POST再读取返回数据。Task的command可以立即返回
  32. _event_loop = None
  33. def _make_response(webio_session: AbstractSession):
  34. return jsonify(webio_session.get_task_commands())
  35. def _remove_expired_sessions(session_expire_seconds):
  36. while _webio_expire:
  37. sid, active_ts = _webio_expire.popitem(last=False)
  38. if time.time() - active_ts < session_expire_seconds:
  39. _webio_expire[sid] = active_ts
  40. _webio_expire.move_to_end(sid, last=False)
  41. break
  42. del _webio_sessions[sid]
  43. _last_check_session_expire_ts = 0 # 上次检查session有效期的时间戳
  44. def _remove_webio_session(sid):
  45. del _webio_sessions[sid]
  46. del _webio_expire[sid]
  47. def _webio_view(target, session_expire_seconds):
  48. """
  49. :param coro_func:
  50. :param session_expire_seconds:
  51. :return:
  52. """
  53. if request.args.get('test'): # 测试接口,当会话使用给予http的backend时,返回 ok
  54. return 'ok'
  55. global _last_check_session_expire_ts, _event_loop
  56. if _event_loop:
  57. asyncio.set_event_loop(_event_loop)
  58. webio_session_id = None
  59. set_header = False
  60. if 'webio-session-id' not in request.headers or not request.headers['webio-session-id']: # start new WebIOSession
  61. set_header = True
  62. webio_session_id = random_str(24)
  63. Session = get_session_implement()
  64. webio_session = Session(target)
  65. _webio_sessions[webio_session_id] = webio_session
  66. _webio_expire[webio_session_id] = time.time()
  67. elif request.headers['webio-session-id'] not in _webio_sessions: # WebIOSession deleted
  68. return jsonify([dict(command='close_session')])
  69. else:
  70. webio_session_id = request.headers['webio-session-id']
  71. webio_session = _webio_sessions[webio_session_id]
  72. if request.method == 'POST': # client push event
  73. webio_session.send_client_event(request.json)
  74. time.sleep(WAIT_MS_ON_POST / 1000.0)
  75. elif request.method == 'GET': # client pull messages
  76. pass
  77. if time.time() - _last_check_session_expire_ts > REMOVE_EXPIRED_SESSIONS_INTERVAL:
  78. _remove_expired_sessions(session_expire_seconds)
  79. _last_check_session_expire_ts = time.time()
  80. response = _make_response(webio_session)
  81. if webio_session.closed():
  82. _remove_webio_session(webio_session_id)
  83. elif set_header:
  84. response.headers['webio-session-id'] = webio_session_id
  85. return response
  86. def webio_view(target, session_expire_seconds, session_type=None):
  87. """获取Flask view"""
  88. if not session_type:
  89. session_type = get_session_implement_for_target(target)
  90. set_session_implement(session_type)
  91. view_func = partial(_webio_view, target=target, session_expire_seconds=session_expire_seconds)
  92. view_func.__name__ = 'webio_view'
  93. return view_func
  94. def _setup_event_loop():
  95. global _event_loop
  96. _event_loop = asyncio.new_event_loop()
  97. _event_loop.set_debug(True)
  98. asyncio.set_event_loop(_event_loop)
  99. _event_loop.run_forever()
  100. def start_server(target, port=8080, host='localhost',
  101. session_type=None,
  102. disable_asyncio=False,
  103. session_expire_seconds=DEFAULT_SESSION_EXPIRE_SECONDS,
  104. debug=False, **flask_options):
  105. """
  106. :param target: task function. It's a coroutine function is use CoroutineBasedSession or
  107. a simple function is use ThreadBasedSession.
  108. :param port: server bind port. set ``0`` to find a free port number to use
  109. :param host: server bind host. ``host`` may be either an IP address or hostname. If it's a hostname,
  110. :param str session_type: 指定 `Session <pywebio.session.AbstractSession>` 的实现。未设置则根据 ``target`` 类型选择合适的实现。
  111. 接受的值为 `pywebio.session.THREAD_BASED` 和 `pywebio.session.COROUTINE_BASED`
  112. :param disable_asyncio: 禁用 asyncio 函数。仅在当 ``session_type=COROUTINE_BASED`` 时有效。
  113. 在Flask backend中使用asyncio需要单独开启一个线程来运行事件循环,
  114. 若程序中没有使用到asyncio中的异步函数,可以开启此选项来避免不必要的资源浪费
  115. :param session_expire_seconds: 会话过期时间。若 session_expire_seconds 秒内没有收到客户端的请求,则认为会话过期。
  116. :param debug: Flask debug mode
  117. :param flask_options: Additional keyword arguments passed to the constructor of ``tornado.web.Application``.
  118. ref: https://www.tornadoweb.org/en/stable/web.html#tornado.web.Application.settings
  119. :return:
  120. """
  121. app = Flask(__name__)
  122. app.route('/io', methods=['GET', 'POST'])(webio_view(target, session_expire_seconds, session_type=session_type))
  123. @app.route('/')
  124. @app.route('/<path:static_file>')
  125. def serve_static_file(static_file='index.html'):
  126. return send_from_directory(STATIC_PATH, static_file)
  127. if not disable_asyncio and get_session_implement() is CoroutineBasedSession:
  128. threading.Thread(target=_setup_event_loop, daemon=True).start()
  129. app.run(host=host, port=port, debug=debug, **flask_options)