fastapi.py 7.2 KB

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