8

我对 Django 及其生态系统比较陌生。我正在使用 django-tastypie 为我们的移动客户端编写 REST api。我已经浏览了网上几乎所有关于如何使用 tastepie 来创建 REST 接口的示例。但它们都不是特定于从客户端发布数据以及您将如何授权客户端。

我使用了 from tastepie.authentication.BasicAuthentication ,如示例中所示。它会打开一个弹出窗口,询问用户名和密码,并在浏览器上正常工作。但我不确定它是否会在移动设备上做同样的事情(具体来说,原生 IOS 应用程序)。当用户请求登录时,如果他或她不使用浏览器而是使用本机应用程序,我不太明白这个弹出窗口将如何显示在他/她的移动设备上。

我完全迷失了这一点,我非常感谢你的帮助。

4

2 回答 2

2

您可以查看源代码并使用例如 ApiKeyAuthentication。您只需发布用户名和 api 密钥即可验证用户。

它看起来可用于 ios 应用程序。这是检查代码的一部分。

def is_authenticated(self, request, **kwargs):
    """
    Finds the user and checks their API key.

    Should return either ``True`` if allowed, ``False`` if not or an
    ``HttpResponse`` if you need something custom.
    """
    from django.contrib.auth.models import User

    username = request.GET.get('username') or request.POST.get('username')
    api_key = request.GET.get('api_key') or request.POST.get('api_key')

    if not username or not api_key:
        return self._unauthorized()

    try:
        user = User.objects.get(username=username)
    except (User.DoesNotExist, User.MultipleObjectsReturned):
        return self._unauthorized()

    request.user = user
    return self.get_key(user, api_key)

https://github.com/toastdriven/django-tastypie/blob/master/tastypie/authentication.py#L128 https://github.com/toastdriven/django-tastypie/blob/master/tastypie/authorization.py#L42

于 2012-01-13T15:34:25.700 回答
0

谢谢您的帮助。

我使用了@Iurii 提到的类似方法。这是我的解决方案。

我写了一个类来处理身份验证并覆盖 is_authenticated 方法。然后我可以在tastepie资源类的元定义中使用这个类。

    从tastepie.authentication 导入BasicAuthentication
    从tastepie.resources 导入资源,模型资源

    # 处理身份验证的类
    类我的身份验证(基本身份验证):
        def is_authenticated(self, request, **kwargs):
            # 把从请求对象中检查用户名和密码的逻辑放在这里
            # 如果用户通过身份验证,则返回 True 否则返回 False

    #tastepie 资源类
    我的资源类(模型资源):
        元类:
            身份验证 = 我的身份验证()

这将确保访问资源的请求将通过您的身份验证代码。

于 2012-02-16T19:57:39.353 回答