Skip to main content
 首页 » 编程设计

python之Django 如何使用 connection_created 信号

2025年05月04日34kenshinobiy

我想知道什么时候连接到我的 Django 数据库,或者我的 Django 服务器什么时候重新启动。我找到了 connection_created Django 信号。描述是:

Sent when the database wrapper makes the initial connection to the database. This is particularly useful if you’d like to send any post connection commands to the SQL backend.

所以我认为使用这个信号对我来说是一个很好的解决方案。我想在建立连接后运行一个函数。我找不到有关此信号用例的任何文档。 connection_created.connect 可能是要使用的函数。此函数接受一堆参数,但相关的参数是 self、receiver、sender 和 weak。有谁知道我如何使用这些参数和这个函数在新的连接实例上运行我的函数?

此外,如果有人有除此信号以外的任何替代解决方案,我很乐意听取他们的意见。

请您参考如下方法:

我将所有表分布在动态 postgres 表模式中,并使用连接信号来设置连接的搜索路径,因为 django 不支持 postgres 模式。

在 myapp/apps.py

from django.db.backends.signals import connection_created 
 
class MyappConfig(AppConfig): 
    name = 'myapp' 
    def ready(self): 
        from myapp.schema_manager import new_connection 
        connection_created.connect(new_connection) 

在 myapp/schema_manager.py

def new_connection(sender, connection, **kwargs): 
    search_path = ['public'] + get_current_schemas()  # fetch the active schemas 
    connection.cursor().execute("SET search_path TO %s;" % ', '.join(search_path) 

根据 the docs ,这个信号接收两个参数:

sender

The database wrapper class – i.e. django.db.backends.postgresql.DatabaseWrapper or django.db.backends.mysql.DatabaseWrapper, etc.

connection

The database connection that was opened. This can be used in a multiple-database configuration to differentiate connection signals from different databases.