代码之家  ›  专栏  ›  技术社区  ›  Kim Stacks

在django 1.11中,如何允许用户登录只读数据库?

  •  5
  • Kim Stacks  · 技术社区  · 8 年前

    我有两个实例,每个都运行自己的postgres数据库。

    一个是用于生产用途。另一个是只读数据库,它从生产数据库执行复制。

    这两个实例运行相同的django 1.11应用程序代码库。

    当我尝试登录到django只读版本时,我无法登录,因为登录操作本身显然执行一些update或insert语句。

    我收到关于只读数据库的内部错误: cannot execute INSERT in a read-only transaction

    如果我想允许用户使用相同的代码库访问只读数据库,我的选项是什么?

    更新

    我已经试过了 django-postgres-readonly . 相同的结果。

    2 回复  |  直到 8 年前
        1
  •  3
  •   Kim Stacks    8 年前

    在与只读数据库对话的代码库上

    步骤1:安装django no last login v0.1.0

    步骤2:内部设置。py添加/更改以下内容

    SESSION_ENGINE = 'django.contrib.sessions.backends.file'
    
    INSTALLED_APPS += [
        'nolastlogin',
    ]
    NO_UPDATE_LAST_LOGIN = True
    

    默认情况下,Django使用数据库作为会话引擎,所以切换到其他类型。

    此外,该插件还可以轻松关闭Django的更新上次登录行为。

    Django自动更新上次登录时间。因为我们想要零数据库写入,所以我们需要使用它。

        2
  •  2
  •   Mattia    8 年前

    Django需要更新如下表 django_session .

    我的建议是为“django表”和“只读表”使用两个不同的数据库

    怎样

    创建一个简单的空sqlite3数据库,并使用 class AuthRouter 用于管理它们。

    对于数据库设置,请使用以下内容:

    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
        },
        'otherdb': {
            'NAME': 'user_data',
            'ENGINE': 'django.db.backends.postgresql',
            'USER': 'ypurusername',
            'PASSWORD': 'yourpassword',
            'HOST': '0.0.0.0'
        }
    }
    

    AuthRouter示例:

    class AuthRouter:
    """
    A router to control all database operations on models in the
    auth application.
    """
    def db_for_read(self, model, **hints):
        """
        Attempts to read auth models go to auth_db.
        """
        if model._meta.db_table == 'django-table':
            return 'defaul'
        return otherdb
    
    def db_for_write(self, model, **hints):
        """
        Attempts to write auth models go to auth_db.
        """
        if model._meta.app_label == 'auth':
            return 'auth_db'
        return None
    
    def allow_migrate(self, db, app_label, model_name=None, **hints):
        """
        Make sure the auth app only appears in the 'auth_db'
        database.
        """
        if app_label == 'migrations':
            return db == 'default'
        return otherdb
    

    Here 指向文档的链接