加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MsSql教程 > 正文

数据库 – Django用户和来自外部来源的身份验证

发布时间:2020-12-12 16:13:14 所属栏目:MsSql教程 来源:网络整理
导读:我有一个Django应用程序,从外部源码完全获取数据(通过HTTP查询).也就是说,我没有本地数据库的选项.会话数据存储在缓存中(在我的开发服务器上我使用一个SQLite数据库,这样就没有错误源).我正在使用流血的Django 1.1svn. 输入问题:我想为用户使用Django自己的
我有一个Django应用程序,从外部源码完全获取数据(通过HTTP查询).也就是说,我没有本地数据库的选项.会话数据存储在缓存中(在我的开发服务器上我使用一个SQLite数据库,这样就没有错误源).我正在使用流血的Django 1.1svn.

输入问题:我想为用户使用Django自己的身份验证系统.

编写自己的身份验证后端似乎很简单,但总是在您有一个本地数据库保存用户的条件下.没有数据库我的主要问题是持久性.

我尝试以下(假设datasource.get()是一个函数返回某种类型的dict):

class ModelBackend (object):
    """Login backend."""

    def authenticate (self,username=None,password=None):
        """Check,if a given user/password combination is valid"""

        data = datasource.get ('login',username,password)
        if data and data['ok']:
            return MyUser (username=username)
        else:
            raise TypeError
            return None

    def get_user (self,username):
        """get data about a specific user"""

        try:
          data = datasource.get ('userdata',username)
          if data and data['ok']:
              return data.user
        except:
            pass
        return None


class MyUser (User):
    """Django user who isn't saved in DB"""

    def save (self):
        return None

但是,MyUser上有意缺少的save()方法似乎打破了登录的会话存储.

MyUser如何看起来像没有本地数据库?

解决方法

好的,这比我想象的要复杂得多.首先,从 http://docs.djangoproject.com/en/dev/howto/auth-remote-user/开始,但是您需要使用自己的后端和用户进行扩展.
from django.contrib.auth.backends import RemoteUserBackend

class MyRemoteUserBackend (RemoteUserBackend):
    # Create a User object if not already in the database?
    create_unknown_user = False

    def get_user (self,user_id):
        user = somehow_create_an_instance_of (MyUser,user_id)
        return user

    def authenticate (self,**credentials):
        check_credentials ()
        user = somehow_create_an_instance_of (MyUser,credentials)
        return user

然后用户:

from django.contrib.auth.models import User

class MyUser (User):

    def save (self):
        """saving to DB disabled"""
        pass

    objects = None # we cannot really use this w/o local DB

    username = ""  # and all the other properties likewise.
                   # They're defined as model.CharField or similar,# and we can't allow that

    def get_group_permissions (self):
        """If you don't make your own permissions module,the default also will use the DB. Throw it away"""
        return [] # likewise with the other permission defs

    def get_and_delete_messages (self):
        """Messages are stored in the DB. Darn!"""
        return []

唷! Django真的不是没有数据库的使用而设计的…

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读