flask.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  1. """
  2. Flask backend
  3. """
  4. import json
  5. import logging
  6. import threading
  7. from flask import Flask, request, send_from_directory, Response
  8. from . import utils
  9. from .httpbased import HttpContext, HttpHandler, run_event_loop
  10. from .remote_access import start_remote_access_service
  11. from .utils import make_applications, cdn_validation
  12. from ..utils import STATIC_PATH, iscoroutinefunction, isgeneratorfunction
  13. from ..utils import get_free_port, parse_file_size
  14. logger = logging.getLogger(__name__)
  15. class FlaskHttpContext(HttpContext):
  16. backend_name = 'flask'
  17. def __init__(self):
  18. self.response = Response()
  19. self.request_data = request.data
  20. def request_obj(self):
  21. """返回当前请求对象"""
  22. return request._get_current_object()
  23. def request_method(self):
  24. """返回当前请求的方法,大写"""
  25. return request.method
  26. def request_headers(self):
  27. """返回当前请求的header字典"""
  28. return request.headers
  29. def request_url_parameter(self, name, default=None):
  30. """返回当前请求的URL参数"""
  31. return request.args.get(name, default=default)
  32. def request_body(self):
  33. return self.request_data
  34. def set_header(self, name, value):
  35. """为当前响应设置header"""
  36. self.response.headers[name] = value
  37. def set_status(self, status: int):
  38. """为当前响应设置http status"""
  39. self.response.status_code = status
  40. def set_content(self, content, json_type=False):
  41. """设置相应的内容
  42. :param content:
  43. :param bool json_type: content是否要序列化成json格式,并将 content-type 设置为application/json
  44. """
  45. # self.response.data accept str and bytes
  46. if json_type:
  47. self.set_header('content-type', 'application/json')
  48. self.response.data = json.dumps(content)
  49. else:
  50. self.response.data = content
  51. def get_response(self):
  52. """获取当前的响应对象,用于在私图函数中返回"""
  53. return self.response
  54. def get_client_ip(self):
  55. """获取用户的ip"""
  56. return request.remote_addr
  57. def webio_view(applications, cdn=True,
  58. session_expire_seconds=None,
  59. session_cleanup_interval=None,
  60. allowed_origins=None, check_origin=None):
  61. """Get the view function for running PyWebIO applications in Flask.
  62. The view communicates with the browser by HTTP protocol.
  63. The arguments of ``webio_view()`` have the same meaning as for :func:`pywebio.platform.flask.start_server`
  64. """
  65. cdn = cdn_validation(cdn, '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. def view_func():
  71. context = FlaskHttpContext()
  72. return handler.handle_request(context)
  73. view_func.__name__ = 'webio_view'
  74. return view_func
  75. def start_server(applications, port=8080, host='', cdn=True,
  76. static_dir=None, remote_access=False,
  77. allowed_origins=None, check_origin=None,
  78. session_expire_seconds=None,
  79. session_cleanup_interval=None,
  80. debug=False,
  81. max_payload_size='200M',
  82. **flask_options):
  83. """Start a Flask server to provide the PyWebIO application as a web service.
  84. :param int session_expire_seconds: Session expiration time, in seconds(default 600s).
  85. If no client message is received within ``session_expire_seconds``, the session will be considered expired.
  86. :param int session_cleanup_interval: Session cleanup interval, in seconds(default 300s).
  87. The server will periodically clean up expired sessions and release the resources occupied by the sessions.
  88. :param bool debug: Flask debug mode.
  89. If enabled, the server will automatically reload for code changes.
  90. :param int/str max_payload_size: Max size of a request body which Flask can accept.
  91. :param flask_options: Additional keyword arguments passed to the ``flask.Flask.run``.
  92. For details, please refer: https://flask.palletsprojects.com/en/1.1.x/api/#flask.Flask.run
  93. The arguments of ``start_server()`` have the same meaning as for :func:`pywebio.platform.tornado.start_server`
  94. """
  95. if not host:
  96. host = '0.0.0.0'
  97. if port == 0:
  98. port = get_free_port()
  99. cdn = cdn_validation(cdn, 'warn')
  100. app = Flask(__name__) if static_dir is None else Flask(__name__, static_url_path="/static",
  101. static_folder=static_dir)
  102. utils.MAX_PAYLOAD_SIZE = app.config['MAX_CONTENT_LENGTH'] = parse_file_size(max_payload_size)
  103. app.add_url_rule('/', 'webio_view', webio_view(
  104. applications=applications, cdn=cdn,
  105. session_expire_seconds=session_expire_seconds,
  106. session_cleanup_interval=session_cleanup_interval,
  107. allowed_origins=allowed_origins,
  108. check_origin=check_origin
  109. ), methods=['GET', 'POST', 'OPTIONS'])
  110. app.add_url_rule('/<path:p>', 'pywebio_static', lambda p: send_from_directory(STATIC_PATH, p))
  111. has_coro_target = any(iscoroutinefunction(target) or isgeneratorfunction(target) for
  112. target in make_applications(applications).values())
  113. if has_coro_target:
  114. threading.Thread(target=run_event_loop, daemon=True).start()
  115. if not debug:
  116. logging.getLogger('werkzeug').setLevel(logging.WARNING)
  117. if remote_access or remote_access == {}:
  118. if remote_access is True: remote_access = {}
  119. start_remote_access_service(**remote_access, local_port=port)
  120. app.run(host=host, port=port, debug=debug, threaded=True, **flask_options)