status = '%d %s' % (response.status_code, response.reason_phrase) response_headers = [ *response.items(), *(('Set-Cookie', c.output(header='')) for c in response.cookies.values()), ] start_response(status, response_headers) if getattr(response, 'file_to_stream', None) isnotNoneand environ.get('wsgi.file_wrapper'): # If `wsgi.file_wrapper` is used the WSGI server does not call # .close on the response, but on the file wrapper. Patch it to use # response.close instead which takes care of closing all files. response.file_to_stream.close = response.close response = environ['wsgi.file_wrapper'](response.file_to_stream, response.block_size) return response
1 2 3 4 5 6 7 8 9 10 11 12 13
# django/http/response.py classHttpResponseBase: defclose(self): for closer in self._resource_closers: try: closer() except Exception: pass # Free resources that were still referenced. self._resource_closers.clear() self.closed = True # 请求结束,触发request_finished信号 signals.request_finished.send(sender=self._handler_class)
# django/db/__init__.py # Register an event to reset saved queries when a Django request is started. defreset_queries(**kwargs): for conn in connections.all(): conn.queries_log.clear()
signals.request_started.connect(reset_queries)
# Register an event to reset transaction state and close connections past # their lifetime. defclose_old_connections(**kwargs): for conn in connections.all(): conn.close_if_unusable_or_obsolete()
classConnectionHandler: def__init__(self, databases=None): """ databases is an optional dictionary of database definitions (structured like settings.DATABASES). """ self._databases = databases # Connections needs to still be an actual thread local, as it's truly # thread-critical. Database backends should use @async_unsafe to protect # their code from async contexts, but this will give those contexts # separate connections in case it's needed as well. There's no cleanup # after async contexts, though, so we don't allow that if we can help it. self._connections = Local(thread_critical=True)
def__getitem__(self, alias): if hasattr(self._connections, alias): return getattr(self._connections, alias)