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

前端之家收集整理的这篇文章主要介绍了数据库 – 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真的不是没有数据库的使用而设计的…

原文链接:https://www.f2er.com/mssql/82709.html

猜你在找的MsSQL相关文章