1

这是我的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
        }
    ]
}

我想做这些改变:

  1. 传递用户名并获取属于该用户名的所有链接。
  2. 我目前正在通过 django admin 添加内容并创建新用户,因为在发布帖子时我总是会遇到错误。我想我可能出错了,所以任何帮助可能是使用我当前的 api 创建新用户的 curl 一行会有所帮助。

编辑:

这是我的新 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 不存在。我检查并重新检查,我没有发现网址有任何问题。

编辑:对我来说这是一个相当愚蠢的错误。我忘记在 urls.py 中注册 UserSignUpResource。

4

1 回答 1

0

1.传递用户名并获取属于该用户名的所有链接

查看基于在 django/tastypie 资源中传递请求变量中的 api 调用过滤资源

要创建用户,请参阅如何以编程方式使用 django-tastypie API 创建或注册用户?

于 2012-10-02T07:06:24.210 回答