fastapi.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. import asyncio
  2. import logging
  3. from functools import partial
  4. import uvicorn
  5. from starlette.applications import Starlette
  6. from starlette.requests import Request
  7. from starlette.responses import HTMLResponse
  8. from starlette.routing import Route, WebSocketRoute, Mount
  9. from starlette.websockets import WebSocket
  10. from starlette.websockets import WebSocketDisconnect
  11. from .tornado import open_webbrowser_on_server_started
  12. from .utils import make_applications, render_page, cdn_validation, OriginChecker
  13. from ..session import CoroutineBasedSession, ThreadBasedSession, register_session_implement_for_target, Session
  14. from ..session.base import get_session_info_from_headers
  15. from ..utils import get_free_port, STATIC_PATH, iscoroutinefunction, isgeneratorfunction, strip_space
  16. logger = logging.getLogger(__name__)
  17. def _webio_routes(applications, cdn, check_origin_func):
  18. """
  19. :param dict applications: dict of `name -> task function`
  20. :param bool/str cdn: Whether to load front-end static resources from CDN
  21. :param callable check_origin_func: check_origin_func(origin, host) -> bool
  22. """
  23. async def http_endpoint(request: Request):
  24. origin = request.headers.get('origin')
  25. if origin and not check_origin_func(origin=origin, host=request.headers.get('host')):
  26. return HTMLResponse(status_code=403, content="Cross origin websockets not allowed")
  27. # Backward compatible
  28. if request.query_params.get('test'):
  29. return HTMLResponse(content="")
  30. app_name = request.query_params.get('app', 'index')
  31. app = applications.get(app_name) or applications['index']
  32. html = render_page(app, protocol='ws', cdn=cdn)
  33. return HTMLResponse(content=html)
  34. async def websocket_endpoint(websocket: WebSocket):
  35. ioloop = asyncio.get_event_loop()
  36. await websocket.accept()
  37. close_from_session_tag = False # session close causes websocket close
  38. def send_msg_to_client(session: Session):
  39. for msg in session.get_task_commands():
  40. ioloop.create_task(websocket.send_json(msg))
  41. def close_from_session():
  42. nonlocal close_from_session_tag
  43. close_from_session_tag = True
  44. ioloop.create_task(websocket.close())
  45. logger.debug("WebSocket closed from session")
  46. session_info = get_session_info_from_headers(websocket.headers)
  47. session_info['user_ip'] = websocket.client.host or ''
  48. session_info['request'] = websocket
  49. session_info['backend'] = 'starlette'
  50. session_info['protocol'] = 'websocket'
  51. app_name = websocket.query_params.get('app', 'index')
  52. application = applications.get(app_name) or applications['index']
  53. if iscoroutinefunction(application) or isgeneratorfunction(application):
  54. session = CoroutineBasedSession(application, session_info=session_info,
  55. on_task_command=send_msg_to_client,
  56. on_session_close=close_from_session)
  57. else:
  58. session = ThreadBasedSession(application, session_info=session_info,
  59. on_task_command=send_msg_to_client,
  60. on_session_close=close_from_session, loop=ioloop)
  61. while True:
  62. try:
  63. msg = await websocket.receive_json()
  64. except WebSocketDisconnect:
  65. if not close_from_session_tag:
  66. # close session because client disconnected to server
  67. session.close(nonblock=True)
  68. logger.debug("WebSocket closed from client")
  69. break
  70. if msg is not None:
  71. session.send_client_event(msg)
  72. return [
  73. Route("/", http_endpoint),
  74. WebSocketRoute("/", websocket_endpoint)
  75. ]
  76. def webio_routes(applications, cdn=True, allowed_origins=None, check_origin=None):
  77. """Get the FastAPI/Starlette routes for running PyWebIO applications.
  78. The API communicates with the browser using WebSocket protocol.
  79. The arguments of ``webio_routes()`` have the same meaning as for :func:`pywebio.platform.fastapi.start_server`
  80. :return: FastAPI/Starlette routes
  81. """
  82. try:
  83. import websockets
  84. except Exception:
  85. raise RuntimeError(strip_space("""
  86. Missing dependency package `websockets` for websocket support.
  87. You can install it with the following command:
  88. pip install websockets
  89. """.strip(), n=8))
  90. applications = make_applications(applications)
  91. for target in applications.values():
  92. register_session_implement_for_target(target)
  93. cdn = cdn_validation(cdn, 'error')
  94. if check_origin is None:
  95. check_origin_func = partial(OriginChecker.check_origin, allowed_origins=allowed_origins or [])
  96. else:
  97. check_origin_func = lambda origin, host: OriginChecker.is_same_site(origin, host) or check_origin(origin)
  98. return _webio_routes(applications=applications, cdn=cdn, check_origin_func=check_origin_func)
  99. def start_server(applications, port=0, host='',
  100. cdn=True, static_dir=None, debug=False,
  101. allowed_origins=None, check_origin=None,
  102. auto_open_webbrowser=False,
  103. **uvicorn_settings):
  104. """Start a FastAPI/Starlette server using uvicorn to provide the PyWebIO application as a web service.
  105. :param bool debug: Boolean indicating if debug tracebacks should be returned on errors.
  106. :param uvicorn_settings: Additional keyword arguments passed to ``uvicorn.run()``.
  107. For details, please refer: https://www.uvicorn.org/settings/
  108. The rest arguments of ``start_server()`` have the same meaning as for :func:`pywebio.platform.tornado.start_server`
  109. """
  110. kwargs = locals()
  111. try:
  112. from starlette.staticfiles import StaticFiles
  113. except Exception:
  114. raise RuntimeError(strip_space("""
  115. Missing dependency package `aiofiles` for static file serving.
  116. You can install it with the following command:
  117. pip install aiofiles
  118. """.strip(), n=8))
  119. if not host:
  120. host = '0.0.0.0'
  121. if port == 0:
  122. port = get_free_port()
  123. cdn = cdn_validation(cdn, 'warn')
  124. if cdn is False:
  125. cdn = '/pywebio_static'
  126. routes = webio_routes(applications, cdn=cdn, allowed_origins=allowed_origins, check_origin=check_origin)
  127. routes.append(Mount('/static', app=StaticFiles(directory=static_dir), name="static"))
  128. routes.append(Mount('/pywebio_static', app=StaticFiles(directory=STATIC_PATH), name="pywebio_static"))
  129. app = Starlette(routes=routes, debug=debug)
  130. if auto_open_webbrowser:
  131. asyncio.get_event_loop().create_task(open_webbrowser_on_server_started('localhost', port))
  132. uvicorn.run(app, host=host, port=port)