これは私のmodels.pyです:
from tastypie.utils.timezone import now
from django.contrib.auth.models import User
from django.db import models
from django.template.defaultfilters import slugify
class Link(models.Model):
user = models.ForeignKey(User)
pub_date = models.DateTimeField(default=now)
title = models.CharField(max_length=200)
slug = models.SlugField()
body = models.TextField()
def __unicode__(self):
return self.title
def save(self, *args, **kwargs):
# For automatic slug generation.
if not self.slug:
self.slug = slugify(self.title)[:50]
return super(Link, self).save(*args, **kwargs)
class OAuthConsumer(models.Model):
name = models.CharField(max_length=255)
key = models.CharField(max_length=255)
secret = models.CharField(max_length=255)
active = models.BooleanField(default=True)
class Meta:
db_table = "api_oauth_consumer"
def __unicode__(self):
return u'%s' % (self.name)
これですべてが機能し、次の応答としてこれを取得します。/api/v1/links/list/?format=json
{
"meta": {
"previous": null,
"total_count": 1,
"offset": 0,
"limit": 20,
"next": null
},
"objects": [
{
"body": "http://www.youtube.com/watch?v=wqQ6BF50AT4&feature=relmfu",
"title": "Youtube",
"slug": "main-kya-karoon",
"user": "/api/v1/users/1/",
"pub_date": "2012-10-01T00:23:53",
"id": 1
}
]
}
これらの変更を加えたい:
- ユーザー名を渡し、そのユーザー名に属するすべてのリンクを取得します。
- 私は現在、コンテンツを追加し、django adminを介して新しいユーザーを作成しています。これは、投稿を行っている間、常にエラーが発生するためです。私は間違っていたかもしれないと思うので、私の現在のAPIを使用して新しいユーザーを作成するためのカールワンライナーが役立つかもしれません。
編集:
これは私の新しいapi.pyです(新しいUserSignUpResourceを作成することにしました):
# myapp/api.py
from django.contrib.auth.models import User
from tastypie.authorization import Authorization
from tastypie import fields
from tastypie.resources import ModelResource, ALL, ALL_WITH_RELATIONS
from links.models import Link
from tastypie.serializers import Serializer
from tastypie.admin import ApiKeyInline
from tastypie.models import ApiAccess, ApiKey
from django.db import models
from tastypie.authentication import ApiKeyAuthentication
from tastypie.models import create_api_key
class UserResource(ModelResource):
class Meta:
queryset = User.objects.all()
resource_name = 'users'
excludes = ['email', 'password', 'is_active', 'is_staff', 'is_superuser']
authorization = Authorization()
allowed_methods = ['post','get']
fields = ['username']
def obj_create(self, bundle, request=None, **kwargs):
try:
bundle = super(CreateUserResource, self).obj_create(bundle, request, **kwargs)
bundle.obj.set_password(bundle.data.get('password'))
bundle.obj.set_username(bundle.data.get('username'))
bundle.obj.save()
except IntegrityError:
raise BadRequest('That username already exists')
return bundle
class LinkResource(ModelResource):
user = fields.ForeignKey(UserResource, 'user')
authorization = Authorization()
class Meta:
queryset = Link.objects.all()
resource_name = 'links/list'
excludes = ['id']
authorization = Authorization()
include_resource_uri = False
excludes = ['limit']
def apply_filters(self,request,applicable_filters):
base_object_list = super(LinkResource, self).apply_filters(request, applicable_filters)
query = request.META.get('HTTP_AUHTORIZATION')
if query:
qset = (
Q(api_key=query))
base_object_list = base_object_list.filter(qset).distinct()
return base_object_list
class UserSignUpResource(ModelResource):
class Meta:
object_class = User
queryset = User.objects.all()
allowed_methods = ['post']
include_resource_uri = False
resource_name = 'newuser'
excludes = ['is_active','is_staff','is_superuser']
authentication = ApiKeyAuthentication()
authorizaton = Authorization()
models.signals.post_save.connect(create_api_key, sender=User)
def obj_create(self,bundle,request=None,**kwargs):
try:
bundle = super(UserSignUpResource, self).obj_create(bundle,request,**kwargs)
bundle.obj.set_password(bundle.data.get('password'))
bundle.obj.save()
except IntegrityError:
raise BadRequest('The username already exists')
return bundle
def apply_authorization_limits(self,request,object_list):
return object_list.filter(id=request.user.id,is_superuser=True)
今私がこれをするとき:
curl -v -X POST -d '{"username" : "puck", "password" : "123456"}' -H "Authorization: ApiKey superusername:linklist" -H "Content-Type: application/json" http://127.0.0.1:8000/api/v1/newuser
これは404エラーになります:URLが存在しません。チェックして再チェックしましたが、URLに問題はありません。
編集:それは私の側ではかなりばかげた間違いでした。UserSignUpResourceをurls.pyに登録するのを忘れていました。