aiohttp.py 8.4 KB

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