aiohttp.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  1. import asyncio
  2. import fnmatch
  3. import json
  4. import logging
  5. import os
  6. import typing
  7. from functools import partial
  8. from urllib.parse import urlparse
  9. from aiohttp import web
  10. from .adaptor import ws as ws_adaptor
  11. from .page import make_applications, render_page
  12. from .remote_access import start_remote_access_service
  13. from .tornado import open_webbrowser_on_server_started
  14. from .utils import cdn_validation, print_listen_address
  15. from ..session import 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
  18. logger = logging.getLogger(__name__)
  19. def _check_origin(origin, allowed_origins, host):
  20. if _is_same_site(origin, host):
  21. return True
  22. return any(
  23. fnmatch.fnmatch(origin, pattern)
  24. for pattern in allowed_origins
  25. )
  26. def _is_same_site(origin, host):
  27. """判断 origin 和 host 是否一致。origin 和 host 都为http协议请求头"""
  28. parsed_origin = urlparse(origin)
  29. origin = parsed_origin.netloc
  30. origin = origin.lower()
  31. # Check to see that origin matches host directly, including ports
  32. return origin == host
  33. class WebSocketConnection(ws_adaptor.WebSocketConnection):
  34. def __init__(self, ws: web.WebSocketResponse, http: web.Request, ioloop):
  35. self.ws = ws
  36. self.http = http
  37. self.ioloop = ioloop
  38. def get_query_argument(self, name) -> typing.Optional[str]:
  39. return self.http.query.getone(name, None)
  40. def make_session_info(self) -> dict:
  41. session_info = get_session_info_from_headers(self.http.headers)
  42. session_info['user_ip'] = self.http.remote
  43. session_info['request'] = self.http
  44. session_info['backend'] = 'aiohttp'
  45. session_info['protocol'] = 'websocket'
  46. return session_info
  47. def write_message(self, message: dict):
  48. msg_str = json.dumps(message)
  49. self.ioloop.create_task(self.ws.send_str(msg_str))
  50. def closed(self) -> bool:
  51. return self.ws.closed
  52. def close(self):
  53. self.ioloop.create_task(self.ws.close())
  54. def _webio_handler(applications, cdn, websocket_settings, reconnect_timeout=0, check_origin_func=_is_same_site):
  55. """
  56. :param dict applications: dict of `name -> task function`
  57. :param bool/str cdn: Whether to load front-end static resources from CDN
  58. :param callable check_origin_func: check_origin_func(origin, host) -> bool
  59. :return: aiohttp Request Handler
  60. """
  61. ws_adaptor.set_expire_second(reconnect_timeout)
  62. async def wshandle(request: web.Request):
  63. ioloop = asyncio.get_event_loop()
  64. asyncio.get_event_loop().create_task(ws_adaptor.session_clean_task())
  65. origin = request.headers.get('origin')
  66. if origin and not check_origin_func(origin=origin, host=request.host):
  67. return web.Response(status=403, text="Cross origin websockets not allowed")
  68. if request.headers.get("Upgrade", "").lower() != "websocket":
  69. # Backward compatible
  70. if request.query.getone('test', ''):
  71. return web.Response(text="")
  72. app_name = request.query.getone('app', 'index')
  73. app = applications.get(app_name) or applications['index']
  74. no_cdn = cdn is True and request.query.getone('_pywebio_cdn', '') == 'false'
  75. html = render_page(app, protocol='ws', cdn=False if no_cdn else cdn)
  76. return web.Response(body=html, content_type='text/html')
  77. ws = web.WebSocketResponse(**websocket_settings)
  78. await ws.prepare(request)
  79. app_name = request.query.getone('app', 'index')
  80. application = applications.get(app_name) or applications['index']
  81. conn = WebSocketConnection(ws, request, ioloop)
  82. handler = ws_adaptor.WebSocketHandler(
  83. connection=conn, application=application, reconnectable=bool(reconnect_timeout), ioloop=ioloop
  84. )
  85. # see: https://github.com/aio-libs/aiohttp/issues/1768
  86. try:
  87. async for msg in ws:
  88. if msg.type in (web.WSMsgType.text, web.WSMsgType.binary):
  89. handler.send_client_data(msg.data)
  90. elif msg.type == web.WSMsgType.close:
  91. raise asyncio.CancelledError()
  92. finally:
  93. handler.notify_connection_lost()
  94. return ws
  95. return wshandle
  96. def webio_handler(applications, cdn=True, reconnect_timeout=0, allowed_origins=None, check_origin=None,
  97. websocket_settings=None):
  98. """Get the `Request Handler <https://docs.aiohttp.org/en/stable/web_quickstart.html#aiohttp-web-handler>`_ coroutine for running PyWebIO applications in aiohttp.
  99. The handler communicates with the browser by WebSocket protocol.
  100. The arguments of ``webio_handler()`` have the same meaning as for :func:`pywebio.platform.aiohttp.start_server`
  101. :return: aiohttp Request Handler
  102. """
  103. applications = make_applications(applications)
  104. for target in applications.values():
  105. register_session_implement_for_target(target)
  106. websocket_settings = websocket_settings or {}
  107. cdn = cdn_validation(cdn, 'error')
  108. if check_origin is None:
  109. check_origin_func = partial(_check_origin, allowed_origins=allowed_origins or [])
  110. else:
  111. check_origin_func = lambda origin, host: _is_same_site(origin, host) or check_origin(origin)
  112. return _webio_handler(applications=applications, cdn=cdn,
  113. check_origin_func=check_origin_func,
  114. reconnect_timeout=reconnect_timeout,
  115. websocket_settings=websocket_settings)
  116. def static_routes(prefix='/'):
  117. """获取用于提供PyWebIO静态文件的aiohttp路由列表
  118. Get the aiohttp routes list for PyWebIO static files hosting.
  119. :param str prefix: The URL path of static file hosting, the default is the root path ``/``
  120. :return: aiohttp routes list
  121. """
  122. files = [os.path.join(STATIC_PATH, d) for d in os.listdir(STATIC_PATH)]
  123. dirs = filter(os.path.isdir, files)
  124. routes = [web.static(prefix + os.path.basename(d), d) for d in dirs]
  125. return routes
  126. def start_server(applications, port=0, host='', debug=False,
  127. cdn=True, static_dir=None, remote_access=False,
  128. reconnect_timeout=0,
  129. allowed_origins=None, check_origin=None,
  130. auto_open_webbrowser=False,
  131. websocket_settings=None,
  132. **aiohttp_settings):
  133. """Start a aiohttp server to provide the PyWebIO application as a web service.
  134. :param dict websocket_settings: The parameters passed to the constructor of ``aiohttp.web.WebSocketResponse``.
  135. For details, please refer: https://docs.aiohttp.org/en/stable/web_reference.html#websocketresponse
  136. :param aiohttp_settings: Additional keyword arguments passed to the constructor of ``aiohttp.web.Application``.
  137. For details, please refer: https://docs.aiohttp.org/en/stable/web_reference.html#application
  138. The rest arguments of ``start_server()`` have the same meaning as for :func:`pywebio.platform.tornado.start_server`
  139. """
  140. kwargs = locals()
  141. if not host:
  142. host = '0.0.0.0'
  143. if port == 0:
  144. port = get_free_port()
  145. cdn = cdn_validation(cdn, 'warn')
  146. handler = webio_handler(applications, cdn=cdn, allowed_origins=allowed_origins, reconnect_timeout=reconnect_timeout,
  147. check_origin=check_origin, websocket_settings=websocket_settings)
  148. app = web.Application(**aiohttp_settings)
  149. app.router.add_routes([web.get('/', handler)])
  150. if static_dir is not None:
  151. app.router.add_routes([web.static('/static', static_dir)])
  152. app.router.add_routes(static_routes())
  153. if auto_open_webbrowser:
  154. asyncio.get_event_loop().create_task(open_webbrowser_on_server_started('127.0.0.1', port))
  155. debug = Session.debug = os.environ.get('PYWEBIO_DEBUG', debug)
  156. if debug:
  157. logging.getLogger("asyncio").setLevel(logging.DEBUG)
  158. print_listen_address(host, port)
  159. if remote_access:
  160. start_remote_access_service(local_port=port)
  161. web.run_app(app, host=host, port=port)