# django.core.handlers.wsgi.py class WSGIHandler(base.BaseHandler): initLock = Lock() request_class = WSGIRequest def __call__(self, environ, start_response): # ..... 省略若干代码 # 触发request_started这个Signal signals.request_started.send(sender=self.__class__, environ=environ) try: request = self.request_class(environ) except UnicodeDecodeError: logger.warning('Bad Request (UnicodeDecodeError)', exc_info=sys.exc_info(), extra={ 'status_code': 400, } ) # 请求结束 # 代码位置:django/http/response.py class HttpResponseBase: """ An HTTP response base class with dictionary-accessed headers. This class doesn't handle content. It should not be used directly. Use the HttpResponse and StreamingHttpResponse subclasses instead. """ def close(self): for closable in self._closable_objects: try: closable.close() except Exception: pass self.closed = True signals.request_finished.send(sender=self._handler_class)
这里只是触发,那么在哪对这些signal进行处理呢?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
# 文件:django.db.__init__.py from django.db.utils import ConnectionHandler connections = ConnectionHandler() # 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() signals.request_started.connect(close_old_connections) signals.request_finished.connect(close_old_connections)
# 文件:django/db/backends/base/base.py classBaseDatabaseWrapper: """ Represents a database connection. """ defconnect(self): """Connects to the database. Assumes that the connection is closed.""" # ....省略其他代码 # 连接数据库时读取配置中的CONN_MAX_AGE max_age = self.settings_dict['CONN_MAX_AGE'] self.close_at = Noneif max_age isNoneelse time.time() + max_age # ....省略其他代码 defclose_if_unusable_or_obsolete(self): """ Closes the current connection if unrecoverable errors have occurred, or if it outlived its maximum age. """ if self.connection isnotNone: # If the application didn't restore the original autocommit setting, # don't take chances, drop the connection. if self.get_autocommit() != self.settings_dict['AUTOCOMMIT']: self.close() return # If an exception other than DataError or IntegrityError occurred # since the last commit / rollback, check if the connection works. if self.errors_occurred: if self.is_usable(): self.errors_occurred = False else: self.close() return if self.close_at isnotNoneand time.time() >= self.close_at: self.close() return