【发布时间】:2019-09-30 08:59:41
【问题描述】:
我正在开发一个包含多个数据库的 Django 项目。在应用程序中,我需要根据用户的请求将数据库连接从开发数据库切换到测试数据库或生产数据库。 (数据库架构是固定不变的!)
我也用这个旧指南 here 试试运气 不工作。在 DB 路由器中,我无法访问 threading.locals。
我也尝试过设置自定义数据库路由器。通过会话变量,我尝试设置连接字符串。要读取 dbRouter 中的用户 Session,我需要确切的 Session 密钥,否则我必须循环抛出所有 Session。
object.using('DB_CONNECTION) 的方法是一个不可接受的解决方案……对于许多依赖项。我想为登录的用户全局设置一个连接,而不给每个模型函数提供数据库连接......。
请告诉我如何解决这个问题。
我应该能够基于一个 db 路由器返回 dbConnection 会话值...
def db_for_read|write|*():
from django.contrib.sessions.backends.db import SessionStore
session = SessionStore(session_key='WhyINeedHereAKey_SessionKeyCouldBeUserId')
return session['app.dbConnection']
更新1: 感谢@victorT 的投入。我只是用给定的例子试了一下。 还没有达到目标……
这是我尝试过的。也许你会看到一个配置错误。
Django Version: 2.1.4
Python Version: 3.6.3
Exception Value: (1146, "Table 'app.myModel' doesn't exist")
.app/views/myView.py
from ..models import myModel
from ..thread_local import thread_local
class myView:
@thread_local(DB_FOR_READ_OVERRIDE='MY_DATABASE')
def get_queryset(self, *args, **kwargs):
return myModel.objects.get_queryset()
.app/myRouter.py
from .thread_local import get_thread_local
class myRouter:
def db_for_read(self, model, **hints):
myDbCon = get_thread_local('DB_FOR_READ_OVERRIDE', 'default')
print('Returning myDbCon:', myDbCon)
return myDbCon
.app/thread_local.py
import threading
from functools import wraps
threadlocal = threading.local()
class thread_local(object):
def __init__(self, **kwargs):
self.options = kwargs
def __enter__(self):
for attr, value in self.options.items():
print(attr, value)
setattr(threadlocal, attr, value)
def __exit__(self, exc_type, exc_value, traceback):
for attr in self.options.keys():
setattr(threadlocal, attr, None)
def __call__(self, test_func):
@wraps(test_func)
def inner(*args, **kwargs):
# the thread_local class is also a context manager
# which means it will call __enter__ and __exit__
with self:
return test_func(*args, **kwargs)
return inner
def get_thread_local(attr, default=None):
""" use this method from lower in the stack to get the value """
return getattr(threadlocal, attr, default)
这是输出:
Returning myDbCon: default
DEBUG (0.000) None; args=None
DEBUG (0.000) None; args=None
DEBUG (0.000) None; args=('2019-05-14 06:13:39.477467', '4agimu6ctbwgykvu31tmdvuzr5u94tgk')
DEBUG (0.001) None; args=(1,)
DB_FOR_READ_OVERRIDE MY_DATABASE # The local_router seems to get the given db Name,
Returning myDbCon: None # But disapears in the Router
DEBUG (0.000) None; args=()
Returning myDbCon: None
DEBUG (0.001) None; args=()
Returning myDbCon: None
DEBUG (0.001) None; args=()
Returning myDbCon: None
DEBUG (0.001) None; args=()
Returning myDbCon: None
DEBUG (0.001) None; args=()
Returning myDbCon: None
DEBUG (0.002) None; args=()
ERROR Internal Server Error: /app/env/list/ # It switches back to the default
Traceback (most recent call last):
File "/.../lib64/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
File "/.../lib64/python3.6/site-packages/django/db/backends/mysql/base.py", line 71, in execute
return self.cursor.execute(query, args)
File "/.../lib64/python3.6/site-packages/MySQLdb/cursors.py", line 255, in execute
self.errorhandler(self, exc, value)
File "/.../lib64/python3.6/site-packages/MySQLdb/connections.py", line 50, in defaulterrorhandler
raise errorvalue
File "/.../lib64/python3.6/site-packages/MySQLdb/cursors.py", line 252, in execute
res = self._query(query)
File "/.../lib64/python3.6/site-packages/MySQLdb/cursors.py", line 378, in _query
db.query(q)
File "/.../lib64/python3.6/site-packages/MySQLdb/connections.py", line 280, in query
_mysql.connection.query(self, query)
_mysql_exceptions.ProgrammingError: (1146, "Table 'app.myModel' doesn't exist")
The above exception was the direct cause of the following exception:
更新 2: 这是使用会话的尝试。
我通过会话中的中间件存储数据库连接。 在我想访问的路由器中,然后是请求的会话。我的期望是,Django 处理这个并且知道请求者。但我必须将会话密钥作为
s = SessionStore(session_key='???')
我没有到达路由器...
.middleware.py
from django.contrib.sessions.backends.file import SessionStore
class myMiddleware:
def process_view(self, request, view_func, view_args, view_kwargs):
s = SessionStore()
s['app.dbConnection'] = view_kwargs['MY_DATABASE']
s.create()
.myRouter.py
class myRouter:
def db_for_read(self, model, **hints):
from django.contrib.sessions.backends.file import SessionStore
s = SessionStore(session_key='???')
return s['app.dbConnection']
这导致与 threading.local 相同...一个空值 :-(
【问题讨论】:
-
这在 Django 2.1 中无效...
-
您能否详细说明您遇到的错误类型?如果您忽略该包并直接在代码中使用relevant file 怎么办?
-
myModel.objects.using('MY_DATABASE').all()是否至少在 django shell 中工作(python manage.py shell然后from app.models import myModel)?有和没有 myRouter.py。听起来您有数据库设置问题。或者,如果 django 正在管理数据库,你可能会错过一些迁移,如果不是,你应该有 `class Meta: managed = False` (docs.djangoproject.com/en/2.2/ref/models/options/#managed) -
这与您尝试做的事情很接近 stackoverflow.com/questions/16215122/… ,只要您将数据库名称添加到中间件中的请求中即可。再加上你正在尝试做的事情听起来更像是一个中间件任务而不是一个视图任务。
标签: django django-models django-database django-middleware django-sessions