fastapi.py 8.5 KB

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