【问题标题】:How to write the django-piston handler to create and return ApiKey?如何编写 django-piston 处理程序来创建和返回 ApiKey?
【发布时间】:2012-08-11 14:11:18
【问题描述】:

我目前正在开发使用 Android 作为客户端和 Django 作为 Web 服务器的项目。我决定使用活塞-django 来创建 REST API 身份验证,并且我已按照以下说明进行操作: What is the right way to write a django-piston client? 并编写我自己的处理程序(api/handlers.py)来创建和返回 ApiKey,如下所示:

class ApiKeyhandler(Basehandler):
    model = ApiKey
    allowed_methods = ('GET', 'POST', 'PUT', 'DELETE')
    fields = ('user', 'keys')

    def create(self, request):
        attrs = self.flatten_dict(request.POST)

        if self.exists(**attrs):
            return rc.DUPLICATE_ENTRY
        else:
            apikey = ApiKey(user=request.user)
            apikey.save()

            return apikey

在 urls.py 中,我为此处理程序使用 HttpBasicAuthentication:

 auth = HttpBasicAuthentication(realm="Authentication API")
 apikey = Resource(handler=ApiKeyHandler, authentication=auth)

但是当我用http://hurl.it测试它时

This is the response from GET

This is the response from POST method

谁能告诉我如何为这个问题编写完整的代码或关于这个问题的任何建议?

【问题讨论】:

    标签: django api rest django-piston


    【解决方案1】:

    由于没有人回答这个问题,我自己想通了,并得到了朋友的帮助。我必须将 ApiKeyHandler 编辑为

    class ApiKeyHandler(BaseHandler):
        model = ApiKey
        allowed_methods = ('GET', 'POST')
        fileds = ('user', 'key')
    
        def read(self, request):
            # Return the API key for request.user
            values_query_set = request.user.keys.values('key')
            api_key = list(values_query_set)[0]['key']
            return HttpResponse(api_key)
    
        def create(self, request):
            #Create a new API Key.
    
            # Check if API key already exists
            if request.user.keys.count() > 0:
                values_query_set = request.user.keys.values('key')
                api_key = list(values_query_set)[0]['key']
                return HttpResponse(api_key)
            else:
                # Create API key
                api_key = ApiKey(user=request.user)
                api_key.save()
            return HttpResponse(api_key)
    

    根据django-piston doc,方法read在GET上调用,methodcreate在POST上调用。因此,当客户端想要创建新的 API 密钥时;如果 API 密钥不存在,客户端需要请求 HTTP POST 来为request.user创建 API 密钥。

    最后在 models.py 中我需要将 ApiKey 模型编辑为

    class ApiKey(models.Model):
        user = models.ForeignKey(User, related_name='keys', unique=True)
        key = models.CharField(max_length=KEY_SIZE, null=True, blank=True)
    
        def save(self, *args, **kwargs):
            self.key = User.objects.make_random_password(length=KEY_SIZE)
    
            while ApiKey.objects.filter(key__exact=self.key).count():
                self.key = User.objects.make_random_password(length=KEY_SIZE)
    
            super(ApiKey, self).save(*args, **kwargs)
    
        def __unicode__(self):
            return self.key
    

    We need to call the "real" save() method

    super(ApiKey, self).save(*args, **kwargs)
    

    APIKeyAuthenticatin 现在可以使用了。

    最后但同样重要的是,在验证用户时,客户端需要请求带有 HEADER ('Authorization', api_key) 的 HTTP 请求。api_key 必须与request.user 匹配。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-30
      • 1970-01-01
      • 2013-11-11
      • 2017-08-02
      相关资源
      最近更新 更多