Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

basehttp.py 5.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  1. """
  2. HTTP server that implements the Python WSGI protocol (PEP 333, rev 1.21).
  3. Based on wsgiref.simple_server which is part of the standard library since 2.5.
  4. This is a simple server for use in testing or debugging Django apps. It hasn't
  5. been reviewed for security issues. DON'T USE IT FOR PRODUCTION USE!
  6. """
  7. import logging
  8. import socket
  9. import socketserver
  10. import sys
  11. from wsgiref import simple_server
  12. from django.core.exceptions import ImproperlyConfigured
  13. from django.core.wsgi import get_wsgi_application
  14. from django.utils.module_loading import import_string
  15. __all__ = ('WSGIServer', 'WSGIRequestHandler')
  16. logger = logging.getLogger('django.server')
  17. def get_internal_wsgi_application():
  18. """
  19. Load and return the WSGI application as configured by the user in
  20. ``settings.WSGI_APPLICATION``. With the default ``startproject`` layout,
  21. this will be the ``application`` object in ``projectname/wsgi.py``.
  22. This function, and the ``WSGI_APPLICATION`` setting itself, are only useful
  23. for Django's internal server (runserver); external WSGI servers should just
  24. be configured to point to the correct application object directly.
  25. If settings.WSGI_APPLICATION is not set (is ``None``), return
  26. whatever ``django.core.wsgi.get_wsgi_application`` returns.
  27. """
  28. from django.conf import settings
  29. app_path = getattr(settings, 'WSGI_APPLICATION')
  30. if app_path is None:
  31. return get_wsgi_application()
  32. try:
  33. return import_string(app_path)
  34. except ImportError as err:
  35. raise ImproperlyConfigured(
  36. "WSGI application '%s' could not be loaded; "
  37. "Error importing module." % app_path
  38. ) from err
  39. def is_broken_pipe_error():
  40. exc_type, exc_value = sys.exc_info()[:2]
  41. return issubclass(exc_type, socket.error) and exc_value.args[0] == 32
  42. class WSGIServer(simple_server.WSGIServer):
  43. """BaseHTTPServer that implements the Python WSGI protocol"""
  44. request_queue_size = 10
  45. def __init__(self, *args, ipv6=False, allow_reuse_address=True, **kwargs):
  46. if ipv6:
  47. self.address_family = socket.AF_INET6
  48. self.allow_reuse_address = allow_reuse_address
  49. super().__init__(*args, **kwargs)
  50. def handle_error(self, request, client_address):
  51. if is_broken_pipe_error():
  52. logger.info("- Broken pipe from %s\n", client_address)
  53. else:
  54. super().handle_error(request, client_address)
  55. class ThreadedWSGIServer(socketserver.ThreadingMixIn, WSGIServer):
  56. """A threaded version of the WSGIServer"""
  57. pass
  58. class ServerHandler(simple_server.ServerHandler):
  59. http_version = '1.1'
  60. def handle_error(self):
  61. # Ignore broken pipe errors, otherwise pass on
  62. if not is_broken_pipe_error():
  63. super().handle_error()
  64. class WSGIRequestHandler(simple_server.WSGIRequestHandler):
  65. protocol_version = 'HTTP/1.1'
  66. def address_string(self):
  67. # Short-circuit parent method to not call socket.getfqdn
  68. return self.client_address[0]
  69. def log_message(self, format, *args):
  70. extra = {
  71. 'request': self.request,
  72. 'server_time': self.log_date_time_string(),
  73. }
  74. if args[1][0] == '4':
  75. # 0x16 = Handshake, 0x03 = SSL 3.0 or TLS 1.x
  76. if args[0].startswith('\x16\x03'):
  77. extra['status_code'] = 500
  78. logger.error(
  79. "You're accessing the development server over HTTPS, but "
  80. "it only supports HTTP.\n", extra=extra,
  81. )
  82. return
  83. if args[1].isdigit() and len(args[1]) == 3:
  84. status_code = int(args[1])
  85. extra['status_code'] = status_code
  86. if status_code >= 500:
  87. level = logger.error
  88. elif status_code >= 400:
  89. level = logger.warning
  90. else:
  91. level = logger.info
  92. else:
  93. level = logger.info
  94. level(format, *args, extra=extra)
  95. def get_environ(self):
  96. # Strip all headers with underscores in the name before constructing
  97. # the WSGI environ. This prevents header-spoofing based on ambiguity
  98. # between underscores and dashes both normalized to underscores in WSGI
  99. # env vars. Nginx and Apache 2.4+ both do this as well.
  100. for k in self.headers:
  101. if '_' in k:
  102. del self.headers[k]
  103. return super().get_environ()
  104. def handle(self):
  105. """Copy of WSGIRequestHandler.handle() but with different ServerHandler"""
  106. self.raw_requestline = self.rfile.readline(65537)
  107. if len(self.raw_requestline) > 65536:
  108. self.requestline = ''
  109. self.request_version = ''
  110. self.command = ''
  111. self.send_error(414)
  112. return
  113. if not self.parse_request(): # An error code has been sent, just exit
  114. return
  115. handler = ServerHandler(
  116. self.rfile, self.wfile, self.get_stderr(), self.get_environ()
  117. )
  118. handler.request_handler = self # backpointer for logging
  119. handler.run(self.server.get_app())
  120. def run(addr, port, wsgi_handler, ipv6=False, threading=False, server_cls=WSGIServer):
  121. server_address = (addr, port)
  122. if threading:
  123. httpd_cls = type('WSGIServer', (socketserver.ThreadingMixIn, server_cls), {})
  124. else:
  125. httpd_cls = server_cls
  126. httpd = httpd_cls(server_address, WSGIRequestHandler, ipv6=ipv6)
  127. if threading:
  128. # ThreadingMixIn.daemon_threads indicates how threads will behave on an
  129. # abrupt shutdown; like quitting the server by the user or restarting
  130. # by the auto-reloader. True means the server will not wait for thread
  131. # termination before it quits. This will make auto-reloader faster
  132. # and will prevent the need to kill the server manually if a thread
  133. # isn't terminating correctly.
  134. httpd.daemon_threads = True
  135. httpd.set_app(wsgi_handler)
  136. httpd.serve_forever()