flask.py 6.6 KB

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