tornado_http.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  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_json(self):
  28. """返回当前请求的json反序列化后的内容,若请求数据不为json格式,返回None"""
  29. try:
  30. return json.loads(self.handler.request.body.decode('utf8'))
  31. except Exception:
  32. return None
  33. def set_header(self, name, value):
  34. """为当前响应设置header"""
  35. self.handler.set_header(name, value)
  36. def set_status(self, status: int):
  37. """为当前响应设置http status"""
  38. self.handler.set_status(status)
  39. def set_content(self, content, json_type=False):
  40. """设置相应的内容
  41. :param content:
  42. :param bool json_type: content是否要序列化成json格式,并将 content-type 设置为application/json
  43. """
  44. # self.response.content accept str and byte
  45. if json_type:
  46. self.set_header('content-type', 'application/json')
  47. self.response = json.dumps(content)
  48. else:
  49. self.response = content
  50. def get_response(self):
  51. """获取当前的响应对象,用于在私图函数中返回"""
  52. return self.response
  53. def get_client_ip(self):
  54. """获取用户的ip"""
  55. return self.handler.request.remote_ip
  56. def get_path(self):
  57. """Get the path patton of the http request uri"""
  58. return self.handler.request.path
  59. def webio_handler(applications, cdn=True,
  60. session_expire_seconds=None,
  61. session_cleanup_interval=None,
  62. allowed_origins=None, check_origin=None):
  63. """Get the ``RequestHandler`` class for running PyWebIO applications in Tornado.
  64. The ``RequestHandler`` communicates with the browser by HTTP protocol.
  65. The arguments of ``webio_handler()`` have the same meaning as for :func:`pywebio.platform.tornado_http.start_server`
  66. .. versionadded:: 1.2
  67. """
  68. cdn = cdn_validation(cdn, 'error') # if CDN is not available, raise error
  69. handler = HttpHandler(applications=applications, cdn=cdn,
  70. session_expire_seconds=session_expire_seconds,
  71. session_cleanup_interval=session_cleanup_interval,
  72. allowed_origins=allowed_origins, check_origin=check_origin)
  73. class MainHandler(tornado.web.RequestHandler):
  74. def options(self):
  75. return self.get()
  76. def post(self):
  77. return self.get()
  78. def get(self):
  79. context = TornadoHttpContext(self)
  80. self.write(handler.handle_request(context))
  81. return MainHandler
  82. def start_server(applications, port=8080, host='localhost',
  83. debug=False, cdn=True, static_dir=None,
  84. allowed_origins=None, check_origin=None,
  85. auto_open_webbrowser=False,
  86. session_expire_seconds=None,
  87. session_cleanup_interval=None,
  88. websocket_max_message_size=None,
  89. websocket_ping_interval=None,
  90. websocket_ping_timeout=None,
  91. **tornado_app_settings):
  92. """Start a Tornado server to provide the PyWebIO application as a web service.
  93. The Tornado server communicates with the browser by HTTP protocol.
  94. :param int session_expire_seconds: Session expiration time, in seconds(default 60s).
  95. If no client message is received within ``session_expire_seconds``, the session will be considered expired.
  96. :param int session_cleanup_interval: Session cleanup interval, in seconds(default 120s).
  97. The server will periodically clean up expired sessions and release the resources occupied by the sessions.
  98. The rest arguments of ``start_server()`` have the same meaning as for :func:`pywebio.platform.tornado.start_server`
  99. .. versionadded:: 1.2
  100. """
  101. if port == 0:
  102. port = get_free_port()
  103. if not host:
  104. host = '0.0.0.0'
  105. cdn = cdn_validation(cdn, 'warn')
  106. kwargs = locals()
  107. set_ioloop(tornado.ioloop.IOLoop.current()) # to enable bokeh app
  108. app_options = ['debug', 'websocket_max_message_size', 'websocket_ping_interval', 'websocket_ping_timeout']
  109. for opt in app_options:
  110. if kwargs[opt] is not None:
  111. tornado_app_settings[opt] = kwargs[opt]
  112. cdn = cdn_validation(cdn, 'warn') # if CDN is not available, warn user and disable CDN
  113. handler = webio_handler(applications, cdn,
  114. session_expire_seconds=session_expire_seconds,
  115. session_cleanup_interval=session_cleanup_interval,
  116. allowed_origins=allowed_origins, check_origin=check_origin)
  117. _, port = _setup_server(webio_handler=handler, port=port, host=host, static_dir=static_dir, **tornado_app_settings)
  118. print('Listen on %s:%s' % (host or '0.0.0.0', port))
  119. if auto_open_webbrowser:
  120. tornado.ioloop.IOLoop.current().spawn_callback(open_webbrowser_on_server_started, host or 'localhost', port)
  121. tornado.ioloop.IOLoop.current().start()