aiohttp.py 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  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 .utils import make_applications, render_page, cdn_validation, deserialize_binary_event
  13. from ..session import CoroutineBasedSession, ThreadBasedSession, register_session_implement_for_target, Session
  14. from ..session.base import get_session_info_from_headers
  15. from ..utils import get_free_port, STATIC_PATH, iscoroutinefunction, isgeneratorfunction
  16. logger = logging.getLogger(__name__)
  17. def _check_origin(origin, allowed_origins, host):
  18. if _is_same_site(origin, host):
  19. return True
  20. return any(
  21. fnmatch.fnmatch(origin, pattern)
  22. for pattern in allowed_origins
  23. )
  24. def _is_same_site(origin, host):
  25. """判断 origin 和 host 是否一致。origin 和 host 都为http协议请求头"""
  26. parsed_origin = urlparse(origin)
  27. origin = parsed_origin.netloc
  28. origin = origin.lower()
  29. # Check to see that origin matches host directly, including ports
  30. return origin == host
  31. def _webio_handler(applications, cdn, websocket_settings, check_origin_func=_is_same_site):
  32. """
  33. :param dict applications: dict of `name -> task function`
  34. :param bool/str cdn: Whether to load front-end static resources from CDN
  35. :param callable check_origin_func: check_origin_func(origin, host) -> bool
  36. :return: aiohttp Request Handler
  37. """
  38. async def wshandle(request: web.Request):
  39. ioloop = asyncio.get_event_loop()
  40. origin = request.headers.get('origin')
  41. if origin and not check_origin_func(origin=origin, host=request.host):
  42. return web.Response(status=403, text="Cross origin websockets not allowed")
  43. if request.headers.get("Upgrade", "").lower() != "websocket":
  44. # Backward compatible
  45. if request.query.getone('test', ''):
  46. return web.Response(text="")
  47. app_name = request.query.getone('app', 'index')
  48. app = applications.get(app_name) or applications['index']
  49. html = render_page(app, protocol='ws', cdn=cdn)
  50. return web.Response(body=html, content_type='text/html')
  51. ws = web.WebSocketResponse(**websocket_settings)
  52. await ws.prepare(request)
  53. close_from_session_tag = False # 是否由session主动关闭连接
  54. def send_msg_to_client(session: Session):
  55. for msg in session.get_task_commands():
  56. msg_str = json.dumps(msg)
  57. ioloop.create_task(ws.send_str(msg_str))
  58. def close_from_session():
  59. nonlocal close_from_session_tag
  60. close_from_session_tag = True
  61. ioloop.create_task(ws.close())
  62. logger.debug("WebSocket closed from session")
  63. session_info = get_session_info_from_headers(request.headers)
  64. session_info['user_ip'] = request.remote
  65. session_info['request'] = request
  66. session_info['backend'] = 'aiohttp'
  67. session_info['protocol'] = 'websocket'
  68. app_name = request.query.getone('app', 'index')
  69. application = applications.get(app_name) or applications['index']
  70. if iscoroutinefunction(application) or isgeneratorfunction(application):
  71. session = CoroutineBasedSession(application, session_info=session_info,
  72. on_task_command=send_msg_to_client,
  73. on_session_close=close_from_session)
  74. else:
  75. session = ThreadBasedSession(application, session_info=session_info,
  76. on_task_command=send_msg_to_client,
  77. on_session_close=close_from_session, loop=ioloop)
  78. # see: https://github.com/aio-libs/aiohttp/issues/1768
  79. try:
  80. async for msg in ws:
  81. if msg.type == web.WSMsgType.text:
  82. data = msg.json()
  83. elif msg.type == web.WSMsgType.binary:
  84. data = deserialize_binary_event(msg.data)
  85. elif msg.type == web.WSMsgType.close:
  86. raise asyncio.CancelledError()
  87. if data is not None:
  88. session.send_client_event(data)
  89. finally:
  90. if not close_from_session_tag:
  91. # close session because client disconnected to server
  92. session.close(nonblock=True)
  93. logger.debug("WebSocket closed from client")
  94. return ws
  95. return wshandle
  96. def webio_handler(applications, cdn=True, allowed_origins=None, check_origin=None, websocket_settings=None):
  97. """Get the `Request Handler <https://docs.aiohttp.org/en/stable/web_quickstart.html#aiohttp-web-handler>`_ coroutine for running PyWebIO applications in aiohttp.
  98. The handler communicates with the browser by WebSocket protocol.
  99. The arguments of ``webio_handler()`` have the same meaning as for :func:`pywebio.platform.aiohttp.start_server`
  100. :return: aiohttp Request Handler
  101. """
  102. applications = make_applications(applications)
  103. for target in applications.values():
  104. register_session_implement_for_target(target)
  105. websocket_settings = websocket_settings or {}
  106. cdn = cdn_validation(cdn, 'error')
  107. if check_origin is None:
  108. check_origin_func = partial(_check_origin, allowed_origins=allowed_origins or [])
  109. else:
  110. check_origin_func = lambda origin, host: _is_same_site(origin, host) or check_origin(origin)
  111. return _webio_handler(applications=applications, cdn=cdn,
  112. check_origin_func=check_origin_func,
  113. websocket_settings=websocket_settings)
  114. def static_routes(prefix='/'):
  115. """获取用于提供PyWebIO静态文件的aiohttp路由列表
  116. Get the aiohttp routes list for PyWebIO static files hosting.
  117. :param str prefix: The URL path of static file hosting, the default is the root path ``/``
  118. :return: aiohttp routes list
  119. """
  120. async def index(request):
  121. return web.FileResponse(path.join(STATIC_PATH, 'index.html'))
  122. files = [path.join(STATIC_PATH, d) for d in listdir(STATIC_PATH)]
  123. dirs = filter(path.isdir, files)
  124. routes = [web.static(prefix + path.basename(d), d) for d in dirs]
  125. routes.append(web.get(prefix, index))
  126. return routes
  127. def start_server(applications, port=0, host='', debug=False,
  128. cdn=True, static_dir=None, remote_access=False,
  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,
  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('localhost', port))
  155. debug = Session.debug = os.environ.get('PYWEBIO_DEBUG', debug)
  156. if debug:
  157. logging.getLogger("asyncio").setLevel(logging.DEBUG)
  158. print('Listen on %s:%s' % (host, port))
  159. if remote_access:
  160. start_remote_access_service(local_port=port)
  161. web.run_app(app, host=host, port=port)