gpt4 book ai didi

python - Django 如何使用 connection_created 信号

转载 作者:太空宇宙 更新时间:2023-11-04 08:40:42 25 4
gpt4 key购买 nike

我想知道什么时候连接到我的 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 可能是要使用的函数。此函数接受一堆参数,但相关的参数是 selfreceiversenderweak。有谁知道我如何使用这些参数和这个函数在新的连接实例上运行我的函数?

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

最佳答案

我将所有表分布在动态 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.

关于python - Django 如何使用 connection_created 信号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45171142/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com