tornado_http.py 6.0 KB

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