flask.py 6.7 KB

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