1
0

tornado_http.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  1. import json
  2. import logging
  3. import tornado.ioloop
  4. import tornado.web
  5. from .httpbased import HttpContext, HttpHandler
  6. from .tornado import set_ioloop, _setup_server, open_webbrowser_on_server_started
  7. from .utils import cdn_validation
  8. from ..utils import get_free_port
  9. logger = logging.getLogger(__name__)
  10. class TornadoHttpContext(HttpContext):
  11. backend_name = 'tornado'
  12. def __init__(self, handler: tornado.web.RequestHandler):
  13. self.handler = handler
  14. self.response = b''
  15. def request_obj(self):
  16. """返回当前请求对象"""
  17. return self.handler.request
  18. def request_method(self):
  19. """返回当前请求的方法,大写"""
  20. return self.handler.request.method.upper()
  21. def request_headers(self):
  22. """返回当前请求的header字典"""
  23. return self.handler.request.headers
  24. def request_url_parameter(self, name, default=None):
  25. """返回当前请求的URL参数"""
  26. return self.handler.get_query_argument(name, default=default)
  27. def request_body(self):
  28. return self.handler.request.body
  29. def set_header(self, name, value):
  30. """为当前响应设置header"""
  31. self.handler.set_header(name, value)
  32. def set_status(self, status: int):
  33. """为当前响应设置http status"""
  34. self.handler.set_status(status)
  35. def set_content(self, content, json_type=False):
  36. """设置相应的内容
  37. :param content:
  38. :param bool json_type: content是否要序列化成json格式,并将 content-type 设置为application/json
  39. """
  40. # self.response.content accept str and byte
  41. if json_type:
  42. self.set_header('content-type', 'application/json')
  43. self.response = json.dumps(content)
  44. else:
  45. self.response = content
  46. def get_response(self):
  47. """获取当前的响应对象,用于在私图函数中返回"""
  48. return self.response
  49. def get_client_ip(self):
  50. """获取用户的ip"""
  51. return self.handler.request.remote_ip
  52. def get_path(self):
  53. """Get the path patton of the http request uri"""
  54. return self.handler.request.path
  55. def webio_handler(applications, cdn=True,
  56. session_expire_seconds=None,
  57. session_cleanup_interval=None,
  58. allowed_origins=None, check_origin=None):
  59. """Get the ``RequestHandler`` class for running PyWebIO applications in Tornado.
  60. The ``RequestHandler`` communicates with the browser by HTTP protocol.
  61. The arguments of ``webio_handler()`` have the same meaning as for :func:`pywebio.platform.tornado_http.start_server`
  62. .. versionadded:: 1.2
  63. """
  64. cdn = cdn_validation(cdn, 'error') # if CDN is not available, raise error
  65. handler = HttpHandler(applications=applications, cdn=cdn,
  66. session_expire_seconds=session_expire_seconds,
  67. session_cleanup_interval=session_cleanup_interval,
  68. allowed_origins=allowed_origins, check_origin=check_origin)
  69. class MainHandler(tornado.web.RequestHandler):
  70. def options(self):
  71. return self.get()
  72. def post(self):
  73. return self.get()
  74. async def get(self):
  75. context = TornadoHttpContext(self)
  76. response = await handler.handle_request_async(context)
  77. self.write(response)
  78. return MainHandler
  79. def start_server(applications, port=8080, host='',
  80. debug=False, cdn=True, static_dir=None,
  81. allowed_origins=None, check_origin=None,
  82. auto_open_webbrowser=False,
  83. session_expire_seconds=None,
  84. session_cleanup_interval=None,
  85. websocket_max_message_size=None,
  86. websocket_ping_interval=None,
  87. websocket_ping_timeout=None,
  88. **tornado_app_settings):
  89. """Start a Tornado server to provide the PyWebIO application as a web service.
  90. The Tornado server communicates with the browser by HTTP protocol.
  91. :param int session_expire_seconds: Session expiration time, in seconds(default 60s).
  92. If no client message is received within ``session_expire_seconds``, the session will be considered expired.
  93. :param int session_cleanup_interval: Session cleanup interval, in seconds(default 120s).
  94. The server will periodically clean up expired sessions and release the resources occupied by the sessions.
  95. The rest arguments of ``start_server()`` have the same meaning as for :func:`pywebio.platform.tornado.start_server`
  96. .. versionadded:: 1.2
  97. """
  98. if port == 0:
  99. port = get_free_port()
  100. if not host:
  101. host = '0.0.0.0'
  102. cdn = cdn_validation(cdn, 'warn')
  103. kwargs = locals()
  104. set_ioloop(tornado.ioloop.IOLoop.current()) # to enable bokeh app
  105. app_options = ['debug', 'websocket_max_message_size', 'websocket_ping_interval', 'websocket_ping_timeout']
  106. for opt in app_options:
  107. if kwargs[opt] is not None:
  108. tornado_app_settings[opt] = kwargs[opt]
  109. cdn = cdn_validation(cdn, 'warn') # if CDN is not available, warn user and disable CDN
  110. handler = webio_handler(applications, cdn,
  111. session_expire_seconds=session_expire_seconds,
  112. session_cleanup_interval=session_cleanup_interval,
  113. allowed_origins=allowed_origins, check_origin=check_origin)
  114. _, port = _setup_server(webio_handler=handler, port=port, host=host, static_dir=static_dir, **tornado_app_settings)
  115. print('Listen on %s:%s' % (host or '0.0.0.0', port))
  116. if auto_open_webbrowser:
  117. tornado.ioloop.IOLoop.current().spawn_callback(open_webbrowser_on_server_started, host or 'localhost', port)
  118. tornado.ioloop.IOLoop.current().start()