标签: tastypie

返回Django对Tastypie资源的评论

我的Django网站有一个Photo模型,代表系统中的照片,我用它Django.contrib.comments来允许用户评论这些.这一切都运行正常,但我想扩展我的Tastypie API,以允许我PhotoResource使用URL 访问评论,例如/api/v1/photo/1/comments1是照片的ID.我能够让URL工作正常,但无论我正在做什么样的过滤,我似乎总是返回完整的注释集,而不仅仅是提供的照片集.我在下面列出了我当前代码API的精选内容:

class CommentResource(ModelResource):
    user = fields.ForeignKey(UserResource, 'user')
    class Meta:
       queryset = Comment.objects.all()
            filtering = {
                'user': ALL_WITH_RELATIONS,
            }

class PhotoResource(ModelResource):
    user = fields.ForeignKey(UserResource, 'user')  
    class Meta:
        queryset = Photo.objects.all()
        filtering = {
            'id': 'exact',
            'user': ALL_WITH_RELATIONS
        }

    def prepend_urls(self):
        return [url(r"^(?P<resource_name>%s)/(?P<pk>\w[\w/-]*)/comments%s$" % (self._meta.resource_name, trailing_slash()), self.wrap_view('get_comments'), name="api_get_comments"),
        ]

    def get_comments(self, request, **kwargs):
        try:
            obj = self.cached_obj_get(request=request, **self.remove_api_resource_names(kwargs))
        except ObjectDoesNotExist:
            return HttpGone()
        except MultipleObjectsReturned:
            return HttpMultipleChoices("More than one resource is found at this URI.") …
Run Code Online (Sandbox Code Playgroud)

django django-comments tastypie

5
推荐指数
1
解决办法
860
查看次数

在django tastypie中使用OneToOneField创建对象

我有两个模型:Project和Album.它们通过oneToOneField相互关联.

相册/ models.py:

class Album(models.Model):
    title = models.CharField(_('title'), max_length=128)
    slug = models.SlugField(_('slug'), unique=True, default='main-gallery')
Run Code Online (Sandbox Code Playgroud)

项目/ models.py

class Project(models.Model):
    title = models.CharField(_('title'), max_length=300)
    slug = models.SlugField(_('slug'), unique=True)

    main_gallery = models.OneToOneField(Album, verbose_name=_('related main album'), related_name='project', unique=True)

@receiver(pre_save, sender=Project)
def create_project(sender, instance=None, **kwargs):
    if instance is None:
    try:
        str(instance.main_gallery)
    except Album.DoesNotExist:
        main_gallery = Album.objects.create(title=''.join((instance.title, ' - ', 'main gallery')))
Run Code Online (Sandbox Code Playgroud)

如果创建了项目,也将为其创建相册.这很好用.但是当我尝试使用django tastypie在我的api中创建一个时它不会工作:

class AlbumResource(ModelResource):
    class Meta:
        queryset = Album.objects.all()
        resource_name = 'album'
        #fields = ['title','slug',]

    def dehydrate_resource_uri(self, bundle):
        return bundle.data['slug']

class ProjectResource(ModelResource):
    main_gallery = …
Run Code Online (Sandbox Code Playgroud)

python django tastypie

5
推荐指数
1
解决办法
2191
查看次数

如何过滤相关对象中的字段?

如果我尝试过滤相关对象中的字段,则Tastypie会返回错误.例如,跑步

curl -H "Accept: application/json" \
     "http://localhost:8080/wordgame/api/v1/rounds/?format=json&players__username=moe"
Run Code Online (Sandbox Code Playgroud)

返回"在'玩家'字段中,查询不允许超过一个级别." 从本质上讲,我正在努力做我目前在Django shell中所做的事情:

Round.objects.all().filter(players__username=moe.username)
Run Code Online (Sandbox Code Playgroud)

我使用以下代码,为简洁起见,我简化了以下代码:

# wordgame/api.py which has tastypie resources
class RoundResource(ModelResource):
    players = fields.ManyToManyField(UserResource, 'players',full=True)
    . . .

    class Meta:
        queryset = Round.objects.all()
        resource_name = 'rounds'
        filtering = {
            'players': ALL,
        }

class UserResource(ModelResource):
    class Meta:
        queryset = User.objects.all()
        resource_name = 'players'
        filtering = {
            'username': ALL,
        }

# wordgame/models.py which has Django models
class Round(models.Model):
    players = models.ManyToManyField(User)
    word = models.CharField(max_length=75)
    . . . 
Run Code Online (Sandbox Code Playgroud)

我假设因为UserResource在字段'username'上定义了一个过滤器,它应该可以工作,但事实并非如此.我甚至尝试将"players__username"添加到RoundResource中的过滤器,但是这也不起作用.

在文档中阅读了有关基本过滤的内容,并查看了GitHub上的代码,但似乎没有任何内容.我还看了一下 …

python django django-models tastypie

5
推荐指数
1
解决办法
3408
查看次数

django tastypie中的嵌套资源

我有2个型号如下

商人

class MerchantProfile(StateModel):

    class Meta:
        verbose_name = "Merchant Profile"
        ordering = ('name',)


    def __unicode__(self):
        return u'%s' % (self.name,)

    user = models.OneToOneField(UserProfile, related_name="merchant_profile")
    payment_card = models.OneToOneField(PaymentCard, related_name="merchant_profile")
    current_state = models.IntegerField('State', choices=STATE_CHOICES)
    name = models.CharField('Merchant Name', max_length=64)
Run Code Online (Sandbox Code Playgroud)

类别

class Category(models.Model):
    merchant = models.ForeignKey(MerchantProfile, related_name="category")
    name = models.CharField(max_length=30)
    is_active=models.BooleanField()
Run Code Online (Sandbox Code Playgroud)

我有资源文件如下

儿童资源

class MerchantCategoryResource(ModelResource):
    api_key = fields.CharField(attribute='merchant__user__api_key', readonly=True)
    class Meta:
        #get username from headers and apply filter query
        queryset = Category.objects.all()
        resource_name = 'merchantcategory'
        #excludes = ['id','email', 'password', 'is_active', 'is_staff', 'is_superuser']
        detail_allowed_methods = …
Run Code Online (Sandbox Code Playgroud)

python django orm tastypie

5
推荐指数
1
解决办法
2784
查看次数

浏览器和Nginx之间HTTP POST的神秘〜1分钟延迟

从客户端javascript发送到我们的服务器时,我们最近经历了一个非常奇怪但非常一致的延迟.

这是我们的技术堆栈,从前到后:

  1. 自定义javascript客户端代码
  2. Backbone.js的
  3. 自定义Backbone.sync()实现
  4. jQuery.ajax()(1.7.2)
  5. 的XmlHttpRequest
  6. 浏览器(在Firefox和Chrome上都经过验证)
  7. 互联网
  8. Nginx前端
  9. 内联网(通过Nginx http://上游)
  10. Nginx后端
  11. Gunicorn(通过Nginx unix://上游插座)
  12. Django 1.4
  13. Django的tastypie

(旁注:您是否曾对网络开发的复杂程度感到敬畏?)

这是事件的时间表:

  1. 客户端代码调用.save()新创建的Backbone APIModel.
  2. 我们的自定义.sync()风向client.send()调度新创建的对象的方式$.ajax().
  3. 生成的XmlHttpRequest POST.该请求显示在浏览器开发工具的网络窗格中,标记为待定.
  4. HTTP请求到达Nginx,后者将其路由到django-tastypie后端.
  5. Tastypie及时,完美地处理请求,创建资源,并返回201 CREATED响应,Location标题指向新资源.
  6. Nginx记录请求并(表面上)发送响应.
  7. 1.1分钟过去了,在此期间,请求仍在"网络"窗格中标记为待处理.
  8. 请求在浏览器的"网络"窗格中标记为已完成.
  9. jQuery xhr触发成功处理程序
  10. 我们的自定义API客户端的成功处理程序检测到201响应代码并触发对该位置的后续GET请求.
  11. 通常的事情发生了,GET迅速响应,最外面的$.Deferred()对象解析,触发任何相关的客户端代码成功处理程序.

其他需要考虑的细节:

  1. 同一堆栈中的GET请求和PUT请求立即解决.
  2. 当通过专用HTTP客户端直接与最外层的Nginx交互时,POST请求与请求中的请求相同,并立即解决.
  3. 删除特殊情况201处理程序和后续GET对该错误没有影响.
  4. 延迟总是 1.1分钟.我曾经console.time()确定延迟在65,000ms范围内变化.
  5. 延迟仅出现在此配置中.它不会出现在我们的开发设置中,它们稍微简单一些.

我正在做的未经证实的假设:

  1. 一旦Nginx记录了一个请求,响应就会被鞠躬并用手写的感谢信发送给客户端.
  2. 这不是浏览器或jQuery中的错误.

请原谅详细的细节,但我已尽力消除变量,目前,我觉得这个问题是以下之一:

  1. 宇宙物理结构的缺陷
  2. 我们头脑中感性模型的缺陷
  3. 我们尚未考虑的其他事情

我希望#3.有任何想法吗?

javascript nginx xmlhttprequest backbone.js tastypie

5
推荐指数
1
解决办法
2139
查看次数

django-tastypie:发布到具有ManytoMany字段且具有完全关系的资源

我正在为一个项目开发一个API,我通过OrderProducts建立了一个关系Order/Products,如下所示:

在models.py中

class Product(models.Model):
    ...

class Order(models.Model):
    products = models.ManyToManyField(Product, verbose_name='Products', through='OrderProducts')
    ...

class OrderProducts(models.Model):
    order = models.ForeignKey(Order)
    product = models.ForeignKey(Product)
    ...
Run Code Online (Sandbox Code Playgroud)

现在,当我通过API加载订单时,我也希望获得相关产品,所以我尝试了这个(使用django-tastypie):

按顺序/ api.py

class OrderResource(ModelResource):
    products = fields.ToManyField('order.api.ProductResource', products, full=True)

    class Meta:
        queryset = Order.objects.all()
        resource_name = 'order'
Run Code Online (Sandbox Code Playgroud)

一切都适用于列出订单资源.我获得了嵌入了产品数据的订单资源.

问题是我无法使用api创建或编辑Order对象.由于我在ManytoMany关系中使用直通模型,因此ManyToManyField(产品)没有.add()方法.但是tastypie试图在发布/向其发送数据时在OrderResource的产品字段上调用.add().

{"error_message": "'ManyRelatedManager' object has no attribute 'add'", "traceback": "Traceback (most recent call last):\n\n  File \"/Library/Python/2.7/site-packages/tastypie/resources.py\", line 192, in wrapper\n    response = callback(request, *args, **kwargs)\n\n  File \"/Library/Python/2.7/site-packages/tastypie/resources.py\", line 397, in dispatch_list\n    return self.dispatch('list', request, **kwargs)\n\n  File \"/Library/Python/2.7/site-packages/tastypie/resources.py\", line 427, …
Run Code Online (Sandbox Code Playgroud)

django tastypie

5
推荐指数
2
解决办法
2460
查看次数

Tastypie REST上的ForeignKey - 模型''具有空属性

我需要列出每个员工的工作时间,但我得到:

模型''具有空属性'work_journey',并且不允许空值.

上:

/休息/ tastypie /雇员/?格式= JSON

models.py

class Employee():
    registration = models.CharField(u'Registration', max_length=20, unique=True)
    work_journey = models.ForeignKey(WorkJourney, null=True, blank=True)
Run Code Online (Sandbox Code Playgroud)

hr.models.py

class WorkJourney(ModelPlus):
    code = models.CharField(max_length=10, null=True, unique=True)
    workinghours = models.CharField(max_length=40)
    excluded = models.BooleanField()

    class Meta:
        db_table='work_journey'
        verbose_name = u'Work Journey'

    def __unicode__(self):
        return self.workinghours
Run Code Online (Sandbox Code Playgroud)

resources.py

from suap.models import Employee
from hr.models import WorkJourney


class WorkJourneyResource(ModelResource):
    class Meta:
        queryset = WorkJourney.objects.all()
        resource_name = 'work_journey'
        authentication = BasicAuthentication()

class EmployeeResource(ModelResource):
    journey = fields.ForeignKey(WorkJourney, 'work_journey')
    class Meta:
        queryset = Employee.objects.all()
        resource_name = …
Run Code Online (Sandbox Code Playgroud)

django rest tastypie

5
推荐指数
1
解决办法
4560
查看次数

从iphone应用程序和移动浏览器注册并登录django后端

我们正在使用iphone应用程序构建Django后端,并且还希望允许通过Web /移动浏览器登录.要求是能够从网站/移动浏览器以及通过iPhone应用程序注册和登录.我还集成了django-registration进行注册,登录,注销等.

什么是首选方法,以便通过iPhone应用程序和移动浏览器进行注册,登录,注销?

讨论最多的方法似乎如下:

  1. 将tastypie用于RESTful API(或任何其他REST框架)(在这种情况下,我假设这意味着为注册和登录创建一个api)
  2. 对于iphone,使用RESTKIT来调用和验证后端以执行登录,注册等.

在我们的案例中,安全性和仅查看用户相关数据的能力非常重要,因为数据非常敏感.

任何建议都非常感谢,肯定也会帮助其他人.

提前致谢.新

django django-registration tastypie

5
推荐指数
1
解决办法
1646
查看次数

如何通过tastypie上传文件/图像

我在开发带有tastypie的api时遇到了问题.我想要的主要是知道是否有办法直接将图像发布到json内的tastypie.

在我的模型中,我现在正在使用ImageField:

  class MyClass(models.Model):
      description = models.TextField()
      user = models.ForeignKey(User)
      photo = models.ImageField(upload_to="image", null=True, blank=True)
Run Code Online (Sandbox Code Playgroud)

然后在我的api文件中:

    class InquiryResource(ModelResource):
        user = fields.ForeignKey(UserResource, 'user' ,full=True)
        photo = fields.FileField(attribute = 'photo', null=True, blank = True)

        class Meta :
            queryset = MyClass.objects.all()
            resource_name = "MyClass"
            authorization = Authorization()
Run Code Online (Sandbox Code Playgroud)

当我发送一个只有用户和描述的基本json时,它运行良好.然后当我去添加关于我的图像的信息时:

    { ... ,
    photo : {
       Content-Type : "image/png",
       file : "base64string", <----- this one contains the file as a long string
       name : "test.png"
    } ...}
Run Code Online (Sandbox Code Playgroud)

我收到一条错误消息:'dict'对象没有属性'_commited'

使用tastypie本地上传文件是否有"干净的方式",还是应该使用Base64FileField?

谢谢

javascript python django file-upload tastypie

5
推荐指数
1
解决办法
1150
查看次数

Django-Tastypie中的Multipart/Form-Data POST,PUT,PATCH

我需要在django中使用tastypie修补用户个人资料图片.我使用Django 1.6,AngularJs,它使用Django的普通Authentication()和DjangoAuthorization()类.

当我尝试使用'CONTENT-TYPE:Multipart/form-data'上传图像时.我收到以下错误.

error_message: "You cannot access body after reading from request's data stream"

首先我知道Tastypie没有官方支持多部分表单数据.我希望有一个猴子补丁或任何有效的东西,直到tastypie支持Multipart-Form Data.

我已经对上面做了一些研究,我已经研究了一些问题:

参考文献:

  1. Django-Tastypie反序列化多部分表单数据
  2. 在Tastypie中访问帖子数据

虽然上面的方法看起来像是一个黑客..我想在我的资源中尝试一下.

我的资源如下:


class UserProfileResource(ModelResource):
    user = fields.ToOneField(UserResource, 'user', full=True)
    profile_img = fields.FileField(attribute="img", null=True, blank=True)

    """docstring for ProfileResource"""
    def alter_list_data_to_serialize(self, request, data):
        if request.GET.get('meta_only'):
            return {'meta': data['meta']}
        return data

    def authorized_read_list(self, object_list, bundle):
        return object_list.filter(user=bundle.request.user).select_related()

    def obj_create(self, bundle, **kwargs):
        return super(UserProfileResource, self).obj_create(bundle, user=bundle.request.user)

    def dehydrate(self, bundle):
        bundle.data['groups'] = [g.name for g in bundle.request.user.groups.all()]
        return bundle

    """Deserialize for multipart Data"""
    def deserialize(self, …
Run Code Online (Sandbox Code Playgroud)

python django tastypie

5
推荐指数
1
解决办法
2466
查看次数