Django动态切换数据库 [英] Django switch database dynamically

查看:507
本文介绍了Django动态切换数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在用户登录时切换数据库。我创建了这个登录信号..但它不工作

 从django.dispatch导入接收器
从django.contrib.auth.signals import user_logged_in
from django.db import connections

@receiver(user_logged_in)
def db_switch(sender,** kwargs):
user_db ='userdb_%s'%kwargs ['user']。username
cursor = connections [user_db] .cursor()

数据库在 settings.py 中定义。我必须让这个游标全球化吗?或者是这样做的方式是错误的吗?



谢谢!

解决方案>

这是错误的做法。



老实说,我不认为在Django中有一个直截了当的稳定的方法。它只是不是为它设计的。



相反,我会设置一个settings_ username .py文件,用于指定名为个人或某事物的辅助数据库。然后,在记录之后,让他们重定向到一个新的域,例如 username .example.com,它使用唯一的.wsgi文件来拉入设置 code> username .py文件。



现在,就系统而言,每个网站是完全独立的,那个用户。只需确保将会话cookie设置为example.com,以便他们在访问用户网站时仍然登录。


I'd like to switch databases upon user login. I've created this login signal.. but it doesn't work

from django.dispatch import receiver
from django.contrib.auth.signals import user_logged_in
from django.db import connections

@receiver(user_logged_in)
def db_switch(sender, **kwargs):
    user_db = 'userdb_%s' % kwargs['user'].username
    cursor = connections[user_db].cursor()

The databases are defined in settings.py. Do I have to make this cursor global? Or is this all the way wrong way of doing it?

Thanks!

解决方案

It's the wrong way of doing it.

Honestly I don't think there is a straightforward, stable way of doing this in Django. It's just not designed for it.

Instead, I'd set up a settings_username.py file for each user, which specifies a secondary database called personal or something. Then, after logging, have them redirect to a new domain, like username.example.com, which uses a unique .wsgi file that pulls in the settingsusername.py file.

Now, as far as the system is concerned, each website is totally separate and unique to that user. Just make sure to set the session cookie to example.com so that they're still logged in when they go to their user website.

这篇关于Django动态切换数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆