python - 在没有数据库的情况下在 Django 中进行身份验证

标签 python django python-3.x django-authentication

我有一个完全从 api 获取数据的 Django 应用程序。所以我不必使用数据库。 session 数据存储在已签名的 cookie 中。我尝试像文档中那样编写自定义用户模型和自定义身份验证后端,但出现以下错误: django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'my_app.MyUser' that has not been installed

我的设置.py:

AUTH_USER_MODEL = 'my_app.MyUser'
AUTHENTICATION_BACKENDS = ('django.contrib.auth.backends.ModelBackend',
                           'my_app.backends.LoginAuthBackend',)

模型.py:

class MyUser(object):
    def save(self):
        pass
    objects = None
    username = ""

在这里,如果尝试使用 django 中的 AbstractUser 而不是 Object,我会收到以下错误:AttributeError: 'NoneType' object has no attribute '_meta'或者数据库表没有退出。

后端.py

class LoginAuthBackend(object):
    def authenticate(self, username=None, password=None):
        if username and password:
           try:
               response = my_auth_function(username, password)
               if response.status_code == 200:
                   token = response.get('my_key')
                   user = MyUser()
                   return user
            except MyCustomException:
                  return None

这让我发疯。看起来像 Django,没有 DB 不好用。

编辑

经过几次尝试,解决这个问题的一个简单方法是删除 'django.contrib.auth.backends.ModelBackend'来自 AUTHENTICATION_BACKENDSAUTH_USER_MODEL从设置。该模型基本上以相同的方式继续。工作顺利

最佳答案

默认的身份验证后端处理器集在 AUTHENTICATION_BACKENDS 设置中定义。请参阅 Customizing authentication 的 Django 文档.

By default, AUTHENTICATION_BACKENDS is set to:

['django.contrib.auth.backends.ModelBackend']

That’s the basic authentication backend that checks the Django users database and queries the built-in permissions.

因此,如果您不想要 django.contrib.auth.backends.ModelBackend 身份验证方法,请将其从列表中删除。您可能希望找到(或创建)一个不同的并将其添加到列表中。

关于python - 在没有数据库的情况下在 Django 中进行身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36556226/

相关文章:

python - Google Calendar API 缺少日历摘要

python - 分组列和计算

Django 两个模型之间的关系

python - Django 管理重定向到自定义 View

Python Selenium-webdriver : for loop returning first element of the list throughout the loop

python - 有没有办法在 Python 2.7 或 numpy 中将图像数据保存为列表/数组?

python - 某些系统上pywinauto引起的Py2Exe错误: "AttributeError: ' module' object has no attribute 'CUIAutomation"

python - 为什么 Python 的 subprocess'popen 在 unix 和 windows 之间如此不同?

python - PostgreSQL Python 将表从一个数据库复制到另一个数据库

python - Django-google-analytics 导入错误