简体   繁体   English

Python Django ORM select 通过 session 变量进行原始查询的自定义数据库

[英]Python Django ORM select custom DB for raw query by session variable

Given the following raw query, inside a view:给定以下原始查询,在视图内:

@login_required(login_url='/login/')
def view(request):
    result = CustomObject.objects.raw("SELECT a, b, c FROM table WHERE d = %(param)s", {
        'param': 123
    })

    ...

    return render(request, 'templates/template.html', {
        'a': 'b'
    })

I use a router to route the query to a DB (use case is read only).我使用路由器将查询路由到数据库(用例是只读的)。

class MyDBRouter(object):
    @staticmethod
    def db_for_read(model, **hints):
        if model == CustomObject:
            return 'customdb'
        return None

    @staticmethod
    def db_for_write(model, **hints):
        return None

I have the available databases configured:我配置了可用的数据库:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    },
    'customdb': {
        'ENGINE': 'django.db.backends.oracle',
        'NAME': 'xxx.yyy.zzz:1234/DB',
        'USER': 'user',
        'PASSWORD': 'pass',
    }
}

Problem:问题:

During login, the User can specify which database he wants to execute the commands on.在登录期间,用户可以指定要在哪个数据库上执行命令。 Depending on the session, I have to use different databases to connect to, therefore I have to specify manually for each request which DB it goes to.根据 session,我必须使用不同的数据库来连接,因此我必须为每个请求手动指定它转到哪个数据库。

Question:问题:

  • How can I access my session variables from a static method of a router?如何从路由器的 static 方法访问我的 session 变量?
  • If using routers is not advised in this specific case, what other options do I have for this problem?如果在这种特定情况下不建议使用路由器,我还有什么其他选择可以解决这个问题?

I don't think you need to do this way我认为你不需要这样做

If you need to use custom database on the fly you can pass it in如果您需要动态使用自定义数据库,您可以将其传入

def login(request):
    # Your logic
    request.session["db-name"] = "customdb"
    # Your logic

def query_view(request):
    db_name = request.session.get("db-name", "default")
    # execute your query with this db_name like 

    MyModel.objects.using(db_name).raw("Your query")

Also if you want your session key to be unique then you can use unique username also like this此外,如果您希望您的 session 密钥是唯一的,那么您也可以像这样使用唯一的用户名

request.session[f"{request.user.username}_{db_name}"] = "customdb"

And access it in other views.并在其他视图中访问它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM