简体   繁体   English

在视图中使用tastypie资源

[英]Using tastypie resource in view

my first question here : 我的第一个问题:

So I'm using tastypie to have api's for my app. 所以我正在使用tastypie来为我的应用程序提供api。

I want to be able to use tastypie to render json and then include that in a django view so that I can bootstrap my app's data. 我希望能够使用tastypie渲染json,然后将其包含在django视图中,以便我可以引导我的应用程序的数据。

There is an example of this in django tastypie cookbook here : http://django-tastypie.readthedocs.org/en/latest/cookbook.html#using-your-resource-in-regular-views 这里有django tastypie食谱中的一个例子: http ://django-tastypie.readthedocs.org/en/latest/cookbook.html#using-your-resource-in-regular-views

The problem is that I CANNOT get this to work, I've tried variants from simpler to more complex and I just cant get it, here some code for my models : 问题是我无法使用它,我尝试了从简单到更复杂的变体,我只是无法得到它,这里是我的模型的一些代码:

class ChatMessage(models.Model):
     content = models.TextField()
     added = models.DateTimeField(auto_now_add=True)

     author = models.ForeignKey(ChatUser, related_name="messages")
     chat_session = models.ForeignKey(ChatSession, related_name="messages")
     answer_to = models.ForeignKey('self', blank=True, null=True)

     flagged = models.BooleanField(blank=True,default=False)
     mododeleted = models.BooleanField(blank=True,default=False)
     mododeleted_by = models.ForeignKey(ChatUser,blank=True,null=True,default=None)
     mododeleted_at = models.DateTimeField(blank=True,null=True,default=None)
     [...]

class ChatSession (models.Model):
    title = models.CharField(max_length=200)
    link_title = models.CharField(max_length=200)
    description = tinymce_models.HTMLField()
    date = models.DateTimeField()
    online = models.BooleanField(default=False)
    next_session = models.BooleanField(default=False)
    meps = models.ManyToManyField(ChatMep)
    uid_newsupdate = models.CharField(max_length=200,blank=True,null=True,default="")
    [...]

and my resources : 和我的资源:

class ChatMessageResource(MyModelResource):
    chat_session = fields.ForeignKey(ChatSessionResource, 'chat_session')

    def renderOne(self,request,pkval):
       data =  self.obj_get(None,pk=pkval)
       dbundle = self.build_bundle(obj=data,request=request)
       return self.serialize(None,self.full_dehydrate(dbundle),'application/json')

    def dehydrate(self, bundle):
        bundle.data['likes'] = bundle.obj.get_likes()
        bundle.data['likes_count'] = len(bundle.data['likes'])
        return bundle

    class Meta:
        authentication = Authentication()
        authorization = Authorization()
        queryset = ChatMessage.objects.all()
        resource_name = 'message'
        fields = ('content', 'added', 'flagged', 'mododeleted','author','answer_to','chat_session')
        filtering = {
            'chat_session': ALL_WITH_RELATIONS,
        }

and my view index : 和我的观点索引:

def index(request):

    cur_sess = get_current_chat_session()

    data1= ChatMessageResource().renderOne(request,723)

    return render_to_response('test.html',
                          { 
                            'all_data' : data1 
                           },
                          context_instance=RequestContext(request))

What I want is my renderOne() function to give me the json of ONE ChatMessageResource And also I'd like a renderAll() function to gice me ALL (or filtered) ChatMessageResources in json. 我想要的是我的renderOne()函数给我一个ChatMessageResource的json而且我想要一个renderAll()函数来给jIII中的所有(或过滤)ChatMessageResources。

And I want to use tastypie internals, I KNOW i could serialize it by myself but that's not the point.. 我想使用tastypie内部,我知道我可以自己序列化,但这不是重点..

Right now the error is : 现在错误是:

NoReverseMatch at /live/

Reverse for 'api_dispatch_detail' with arguments '()' and keyword arguments '{'pk': 14L, 'resource_name': 'session'}' not found.

I'm just getting crazy, I've been trying for hours. 我只是疯了,我已经尝试了几个小时。

So please, how to get ONE/ALL resource as JSON by code using tastypie in a django view ! 那么请问,如何在django视图中使用tastypie通过代码获取ONE / ALL资源作为JSON!

If It's not clear or I need to clarify, please just ask, thanks 如果不清楚或我需要澄清,请问,谢谢

Really what I want to do is to be able to get the JSON returned by an API url I created, but from code, not by visiting the url .. So If I have /api/v1/messages/?chat_session=14 which return a list of messages, I want to be able to do the same by code (and not by fetching the url with curl or something please). 我真正想做的是能够获取我创建的API网址返回的JSON,但是从代码中获取,而不是通过访问网址。所以如果我有/api/v1/messages/?chat_session=14哪个返回一个消息列表,我希望能够通过代码执行相同的操作(而不是通过curl或其他东西获取url)。

Note : definition of ModelResource.obj_get from https://github.com/toastdriven/django-tastypie/blob/master/tastypie/resources.py 注意:从https://github.com/toastdriven/django-tastypie/blob/master/tastypie/resources.py定义ModelResource.obj_get

def obj_get(self, request=None, **kwargs):
            """
    A ORM-specific implementation of ``obj_get``.

    Takes optional ``kwargs``, which are used to narrow the query to find
    the instance.
    """
            try:
                base_object_list = self.get_object_list(request).filter(**kwargs)
                object_list = self.apply_authorization_limits(request, base_object_list)
                stringified_kwargs = ', '.join(["%s=%s" % (k, v) for k, v in kwargs.items()])

                if len(object_list) <= 0:
                    raise self._meta.object_class.DoesNotExist("Couldn't find an instance of '%s' which matched '%s'." % (self._meta.object_class.__name__, stringified_kwargs))
                elif len(object_list) > 1:
                    raise MultipleObjectsReturned("More than '%s' matched '%s'." % (self._meta.object_class.__name__, stringified_kwargs))

                return object_list[0]
            except ValueError:
                raise NotFound("Invalid resource lookup data provided (mismatched type).")

So here I found the solution, the problem was with url resolving ... I needed to add 所以在这里我找到了解决方案,问题在于url解析......我需要添加

def get_resource_uri(self, bundle_or_obj):
   return '/api/v1/%s/%s/' % (self._meta.resource_name,bundle_or_obj.obj.id)

to the related object (session here) in order for it to work (don't ask why!) 到相关的对象(这里的会话),以使其工作(不要问为什么!)

So here is my working solution for renderDetail and renderList : 所以这是我为renderDetail和renderList工作的解决方案:

def renderDetail(self,pkval):
    request = HttpRequest()
    request.GET = {'format': 'json'}
    resp =  self.get_detail(request, pk=pkval)
    return resp.content


def renderList(self,options={}):
    request = HttpRequest()
    request.GET = {'format': 'json'}
    if len(options) > 0:
        request.GET.update(options)

    resp = self.get_list(request)
    return resp.content

And here is an example usage : 以下是一个示例用法:

cmr = ChatMessageResource()

dataOne= cmr.renderDetail("723")

dataAll = cmr.renderList({'limit':'0','chat_session':cur_sess.pk})

https://github.com/toastdriven/django-tastypie/issues/962 https://github.com/toastdriven/django-tastypie/issues/962

I've found that obj_get method needs a bundled request object. 我发现obj_get方法需要一个捆绑的请求对象。 See the link. 请参阅链接。

def user_detail(request, username):
    ur = UserResource()
    # Add this request bundle to the obj_get() method as shown.
    req_bundle = ur.build_bundle(request=request)
    user = ur.obj_get(req_bundle, username=username)
    ....

Your problem seems to be here: 你的问题似乎在这里:

data =  self.obj_get(None,pk=pkval)

The parameters to obj_get should be kwargs that can be passed directly to a standard get . obj_get的参数应该是可以直接传递给标准get kwargs。 None should not be in there. None人不应该在那里。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM