Browse Source

use `session_type` parameter in `start_server` to select Session implement

wangweimin 5 years ago
parent
commit
17cdb6378b

+ 2 - 2
pywebio/__init__.py

@@ -12,8 +12,8 @@ from .platform import start_server
 from . import input
 from . import output
 from .session import (
-    set_session_implement, run_async, run_asyncio_coroutine, register_thread,
-    ThreadBasedSession, CoroutineBasedSession
+    run_async, run_asyncio_coroutine, register_thread,
+    THREAD_BASED, COROUTINE_BASED
 )
 from .exceptions import SessionException, SessionClosedException, SessionNotFoundException
 from .utils import STATIC_PATH

+ 3 - 3
pywebio/demos/zh/overview.py

@@ -6,7 +6,7 @@ import asyncio
 from datetime import datetime
 from functools import partial
 
-from pywebio import start_server, run_async, set_session_implement, CoroutineBasedSession
+from pywebio import start_server, run_async, COROUTINE_BASED
 from pywebio.input import *
 from pywebio.output import *
 
@@ -388,5 +388,5 @@ if __name__ == '__main__':
     parser.add_argument('--port', type=int, default=0, help='server bind port')
     args = parser.parse_args()
 
-    set_session_implement(CoroutineBasedSession)
-    start_server(feature_overview, host=args.host, port=args.port, auto_open_webbrowser=True)
+    start_server(feature_overview, host=args.host, port=args.port, auto_open_webbrowser=True,
+                 session_type=COROUTINE_BASED)

+ 7 - 3
pywebio/platform/flask.py

@@ -128,14 +128,18 @@ def _setup_event_loop():
     _event_loop.run_forever()
 
 
-def start_flask_server(coro_func, port=8080, host='localhost', disable_asyncio=False,
+def start_flask_server(coro_func, port=8080, host='localhost',
+                       session_type=None,
+                       disable_asyncio=False,
                        session_expire_seconds=DEFAULT_SESSION_EXPIRE_SECONDS,
                        debug=False, **flask_options):
     """
     :param coro_func:
     :param port:
     :param host:
-    :param disable_asyncio: 禁用 asyncio 函数。仅在使用 CoroutineBasedSession 会话实现中有效。
+    :param str session_type: Session <pywebio.session.AbstractSession>` 的实现,默认为基于线程的会话实现。
+        接受的值为 `pywebio.session.THREAD_BASED` 和 `pywebio.session.COROUTINE_BASED`
+    :param disable_asyncio: 禁用 asyncio 函数。仅在当 ``session_type=COROUTINE_BASED`` 时有效。
         在Flask backend中使用asyncio需要单独开启一个线程来运行事件循环,
         若程序中没有使用到asyncio中的异步函数,可以开启此选项来避免不必要的资源浪费
     :param session_expire_seconds:
@@ -143,7 +147,7 @@ def start_flask_server(coro_func, port=8080, host='localhost', disable_asyncio=F
     :param flask_options:
     :return:
     """
-    mark_server_started()
+    mark_server_started(session_type)
 
     app = Flask(__name__)
     app.route('/io', methods=['GET', 'POST'])(webio_view(coro_func, session_expire_seconds))

+ 4 - 1
pywebio/platform/tornado.py

@@ -86,6 +86,7 @@ def _setup_server(webio_handler, port=0, host='', **tornado_app_settings):
 
 def start_server(target, port=0, host='', debug=False,
                  auto_open_webbrowser=False,
+                 session_type=None,
                  websocket_max_message_size=None,
                  websocket_ping_interval=None,
                  websocket_ping_timeout=None,
@@ -100,6 +101,8 @@ def start_server(target, port=0, host='', debug=False,
         set empty string or to listen on all available interfaces.
     :param bool debug: Tornado debug mode
     :param bool auto_open_webbrowser: Whether or not auto open web browser when server is started.
+    :param str session_type: `Session <pywebio.session.AbstractSession>` 的实现,默认为基于线程的会话实现。
+        接受的值为 `pywebio.session.THREAD_BASED` 和 `pywebio.session.COROUTINE_BASED`
     :param int websocket_max_message_size: Max bytes of a message which Tornado can accept.
         Messages larger than the ``websocket_max_message_size`` (default 10MiB) will not be accepted.
     :param int websocket_ping_interval: If set to a number, all websockets will be pinged every n seconds.
@@ -114,7 +117,7 @@ def start_server(target, port=0, host='', debug=False,
     """
     kwargs = locals()
 
-    mark_server_started()
+    mark_server_started(session_type)
 
     app_options = ['debug', 'websocket_max_message_size', 'websocket_ping_interval', 'websocket_ping_timeout']
     for opt in app_options:

+ 15 - 7
pywebio/session/__init__.py

@@ -1,29 +1,36 @@
 import threading
 from functools import wraps
 
-from .coroutinebased import CoroutineBasedSession
 from .base import AbstractSession
+from .coroutinebased import CoroutineBasedSession
 from .threadbased import ThreadBasedSession, DesignatedThreadSession
 from ..exceptions import SessionNotFoundException
 
+THREAD_BASED = 'ThreadBased'
+COROUTINE_BASED = 'CoroutineBased'
+
 _session_type = ThreadBasedSession
 
-__all__ = ['run_async', 'run_asyncio_coroutine', 'register_thread']
+__all__ = ['run_async', 'run_asyncio_coroutine', 'register_thread', 'THREAD_BASED', 'COROUTINE_BASED']
 
 _server_started = False
 
 
-def mark_server_started():
+def mark_server_started(session_type_name=None):
     """标记服务端已经启动. 仅用于PyWebIO内部使用"""
     global _server_started
     _server_started = True
 
+    if session_type_name is not None:
+        _set_session_implement(session_type_name)
 
-def set_session_implement(session_type):
+
+def _set_session_implement(session_type_name):
     """设置会话实现类. 仅用于PyWebIO内部使用"""
     global _session_type
-    assert session_type in [ThreadBasedSession, CoroutineBasedSession, DesignatedThreadSession]
-    _session_type = session_type
+    sessions = {THREAD_BASED: ThreadBasedSession, COROUTINE_BASED: CoroutineBasedSession}
+    assert session_type_name in sessions, ValueError('No "%s" Session type ' % session_type_name)
+    _session_type = sessions[session_type_name]
 
 
 def get_session_implement():
@@ -32,8 +39,9 @@ def get_session_implement():
 
 
 def _start_script_mode_server():
+    global _session_type
     from ..platform import start_server_in_current_thread_session
-    set_session_implement(DesignatedThreadSession)
+    _session_type = DesignatedThreadSession
     start_server_in_current_thread_session()