django.py 7.0 KB

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