django.py 6.8 KB

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