django.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. import json
  2. import logging
  3. import os
  4. import threading
  5. from django.http import HttpResponse, HttpRequest
  6. from . import page
  7. from ..session import Session
  8. from .adaptor.http import HttpContext, HttpHandler, run_event_loop
  9. from .remote_access import start_remote_access_service
  10. from .page import make_applications
  11. from .utils import cdn_validation, print_listen_address
  12. from ..utils import STATIC_PATH, iscoroutinefunction, isgeneratorfunction, get_free_port, parse_file_size
  13. logger = logging.getLogger(__name__)
  14. class DjangoHttpContext(HttpContext):
  15. backend_name = 'django'
  16. def __init__(self, request: HttpRequest):
  17. self.request = request
  18. self.response = HttpResponse()
  19. def request_obj(self):
  20. """返回当前请求对象"""
  21. return self.request
  22. def request_method(self):
  23. """返回当前请求的方法,大写"""
  24. return self.request.method
  25. def request_headers(self):
  26. """返回当前请求的header字典"""
  27. return self.request.headers
  28. def request_url_parameter(self, name, default=None):
  29. """返回当前请求的URL参数"""
  30. return self.request.GET.get(name, default=default)
  31. def request_body(self):
  32. return self.request.body
  33. def set_header(self, name, value):
  34. """为当前响应设置header"""
  35. self.response[name] = value
  36. def set_status(self, status: int):
  37. """为当前响应设置http status"""
  38. self.response.status_code = status
  39. def set_content(self, content, json_type=False):
  40. """设置相应的内容
  41. :param content:
  42. :param bool json_type: content是否要序列化成json格式,并将 content-type 设置为application/json
  43. """
  44. # self.response.content accept str and byte
  45. if json_type:
  46. self.set_header('content-type', 'application/json')
  47. self.response.content = json.dumps(content)
  48. else:
  49. self.response.content = content
  50. def get_response(self):
  51. """获取当前的响应对象,用于在私图函数中返回"""
  52. return self.response
  53. def get_client_ip(self):
  54. """获取用户的ip"""
  55. return self.request.META.get('REMOTE_ADDR')
  56. def webio_view(applications, cdn=True,
  57. session_expire_seconds=None,
  58. session_cleanup_interval=None,
  59. allowed_origins=None, check_origin=None):
  60. """Get the view function for running PyWebIO applications in Django.
  61. The view communicates with the browser by HTTP protocol.
  62. The arguments of ``webio_view()`` have the same meaning as for :func:`pywebio.platform.flask.webio_view`
  63. """
  64. cdn = cdn_validation(cdn, 'error')
  65. handler = HttpHandler(applications=applications, cdn=cdn,
  66. session_expire_seconds=session_expire_seconds,
  67. session_cleanup_interval=session_cleanup_interval,
  68. allowed_origins=allowed_origins, check_origin=check_origin)
  69. from django.views.decorators.csrf import csrf_exempt
  70. @csrf_exempt
  71. def view_func(request):
  72. context = DjangoHttpContext(request)
  73. return handler.handle_request(context)
  74. view_func.__name__ = 'webio_view'
  75. return view_func
  76. urlpatterns = []
  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. debug=False, max_payload_size='200M', **django_options):
  83. """Get the Django WSGI app for running PyWebIO applications.
  84. The arguments of ``wsgi_app()`` have the same meaning as for :func:`pywebio.platform.django.start_server`
  85. """
  86. global urlpatterns
  87. from django.conf import settings
  88. from django.core.wsgi import get_wsgi_application
  89. from django.urls import path
  90. from django.utils.crypto import get_random_string
  91. from django.views.static import serve
  92. cdn = cdn_validation(cdn, 'warn')
  93. debug = Session.debug = os.environ.get('PYWEBIO_DEBUG', debug)
  94. max_payload_size = parse_file_size(max_payload_size)
  95. page.MAX_PAYLOAD_SIZE = max_payload_size
  96. django_options.update(dict(
  97. DEBUG=debug,
  98. ALLOWED_HOSTS=["*"], # Disable host header validation
  99. ROOT_URLCONF=__name__, # Make this module the urlconf
  100. SECRET_KEY=get_random_string(10), # We aren't using any security features but Django requires this setting
  101. DATA_UPLOAD_MAX_MEMORY_SIZE=max_payload_size
  102. ))
  103. django_options.setdefault('LOGGING', {
  104. 'version': 1,
  105. 'disable_existing_loggers': False,
  106. 'formatters': {
  107. 'simple': {
  108. 'format': '[%(asctime)s] %(message)s'
  109. },
  110. },
  111. 'handlers': {
  112. 'console': {
  113. 'class': 'logging.StreamHandler',
  114. 'formatter': 'simple'
  115. },
  116. },
  117. 'loggers': {
  118. 'django.server': {
  119. 'level': 'INFO' if debug else 'WARN',
  120. 'handlers': ['console'],
  121. },
  122. },
  123. })
  124. settings.configure(**django_options)
  125. webio_view_func = webio_view(
  126. applications=applications, cdn=cdn,
  127. session_expire_seconds=session_expire_seconds,
  128. session_cleanup_interval=session_cleanup_interval,
  129. allowed_origins=allowed_origins,
  130. check_origin=check_origin
  131. )
  132. urlpatterns = [
  133. path(r"", webio_view_func),
  134. path(r'<path:path>', serve, {'document_root': STATIC_PATH}),
  135. ]
  136. if static_dir is not None:
  137. urlpatterns.insert(0, path(r'static/<path:path>', serve, {'document_root': static_dir}))
  138. return get_wsgi_application()
  139. def start_server(applications, port=8080, host='', cdn=True,
  140. static_dir=None, remote_access=False,
  141. allowed_origins=None, check_origin=None,
  142. session_expire_seconds=None,
  143. session_cleanup_interval=None,
  144. debug=False, max_payload_size='200M', **django_options):
  145. """Start a Django server to provide the PyWebIO application as a web service.
  146. :param bool debug: Django debug mode.
  147. See `Django doc <https://docs.djangoproject.com/en/3.0/ref/settings/#debug>`_ for more detail.
  148. :param django_options: Additional settings to django server.
  149. For details, please refer: https://docs.djangoproject.com/en/3.0/ref/settings/ .
  150. Among them, ``DEBUG``, ``ALLOWED_HOSTS``, ``ROOT_URLCONF``, ``SECRET_KEY`` are set by PyWebIO and cannot be specified in ``django_options``.
  151. The rest arguments of ``start_server()`` have the same meaning as for :func:`pywebio.platform.flask.start_server`
  152. """
  153. if port == 0:
  154. port = get_free_port()
  155. if not host:
  156. host = '0.0.0.0'
  157. max_payload_size = parse_file_size(max_payload_size)
  158. app = wsgi_app(applications, cdn=cdn, static_dir=static_dir, allowed_origins=allowed_origins,
  159. check_origin=check_origin, session_expire_seconds=session_expire_seconds,
  160. session_cleanup_interval=session_cleanup_interval,
  161. debug=debug, max_payload_size=max_payload_size, **django_options)
  162. print_listen_address(host, port)
  163. if remote_access:
  164. start_remote_access_service(local_port=port)
  165. use_tornado_wsgi = os.environ.get('PYWEBIO_DJANGO_WITH_TORNADO', True)
  166. if use_tornado_wsgi:
  167. import tornado.wsgi
  168. container = tornado.wsgi.WSGIContainer(app)
  169. http_server = tornado.httpserver.HTTPServer(container, max_buffer_size=max_payload_size)
  170. http_server.listen(port, address=host)
  171. tornado.ioloop.IOLoop.current().start()
  172. else:
  173. from django.core.management import call_command
  174. has_coro_target = any(iscoroutinefunction(target) or isgeneratorfunction(target) for
  175. target in make_applications(applications).values())
  176. if has_coro_target:
  177. threading.Thread(target=run_event_loop, daemon=True).start()
  178. call_command('runserver', '%s:%d' % (host, port))