1
0

aiohttp.py 7.8 KB

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