Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Since nobody answer this question, I figured it out myself and some help from my friend. I have to edit ApiKeyHandler to</p> <pre><code>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() &gt; 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) </code></pre> <p>According to <a href="https://bitbucket.org/jespern/django-piston/wiki/Documentation#!resources" rel="nofollow">django-piston doc</a> method<code>read</code>is called on GET and method<code>create</code>is called on POST. Thus, when client want to create new API key; client need to request HTTP POST to create API key for<code>request.user</code>if the API key is not already exists.</p> <p>Finally in models.py I need to edit the ApiKey model to</p> <pre><code>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 </code></pre> <p><a href="https://docs.djangoproject.com/en/dev/topics/db/models/#overriding-predefined-model-methods" rel="nofollow">We need to call the "real" save() method</a></p> <pre><code>super(ApiKey, self).save(*args, **kwargs) </code></pre> <p>and APIKeyAuthenticatin is work now.</p> <p>Last but not least, when authenticating user, client need to request the HTTP request with HEADER ('Authorization', api_key).<code>api_key</code> must match with the<code>request.user</code>.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload