我正在尝试将 Django 与非 ORM 数据源一起使用,并且通过我的自定义后端访问其他资源而无需任何身份验证是成功的,现在我需要引入用户身份验证。没有本地数据库。当我收到一个请求(例如,一个使用用户名和密码的 cURL 命令)时,我需要对远程 URL 执行 HTTP 基本身份验证,成功后,我应该返回一个本地创建的用户对象,它只有一个用户名,没什么特别的. 所以在我的 Tastypie 资源中,我写了这样的内容:
class dict2obj(object):
"""
Convert dictionary to object
@source http://stackoverflow.com/a/1305561/383912
"""
def __init__(self, d):
self.__dict__['d'] = d
def __getattr__(self, key):
value = self.__dict__['d'][key]
if type(value) == type({}):
return dict2obj(value)
return value
class RemoteAuth(Authentication):
def is_authenticated(self, request, **kwargs):
username = request.user.username
password = request.user.password
r = requests.get(AUTHENTICATION_URL, auth=(username, password))
if r.status_code == 200:
return True
return False
class UserResource(Resource):
username = fields.CharField(attribute='username')
class Meta:
resource_name = 'user'
authentication = RemoteAuth()
authorization = Authorization()
def obj_get_list(self, request=None, **kwargs):
result = []
posts.append(dict2obj(
{
'username': request.POST.get('username'),
}
))
return result
但这当然是行不通的,因为身份验证对象无法获得这样的密码。请提出一种在不涉及任何本地数据库的情况下处理删除用户身份验证的好方法。