tornado_http.py 5.9 KB

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