flask.py 6.5 KB

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