fastapi.py 8.4 KB

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