使用从其它视图tastypie API [英] Using tastypie api from other views

查看:159
本文介绍了使用从其它视图tastypie API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我打电话从普通的Django意见tastypie API。

I am calling tastypie api from normal django views.

def test(request):

    view = resolve("/api/v1/albumimage/like/user/%d/" % 2 )

    accept =  request.META.get("HTTP_ACCEPT")
    accept += ",application/json"
    request.META["HTTP_ACCEPT"] = accept   
    res = view.func(request, **view.kwargs)

    return HttpResponse(res._container)

鉴于使用tastypie资源结果
我的服务器上调用的API,从另一种观点认为

实现同样的事情,但似乎更难。

achieve the same thing but seems harder.

是我的API调用接受的方式是什么?结果
此外,这将是真棒,如果我能得到的结果在Python字典,而不是JSON。结果
可能吗?

Is my way of calling api acceptable?
Besides, it would be awesome if I could get the result in python dictionary instead of json.
Is it possible?

推荐答案

如果你需要一本字典,这意味着你必须更好地设计应用程序。不要做重要的东西在你的意见,也没有在Tastypie方法。重构它有共同的funcionality。

If you need a dictionary, it means that you must design your application better. Don't do important stuff in your views, nor in the Tastypie methods. Refactor it to have common funcionality.

作为一般规则,的意见一定要小。不超过15行。这使code可读,可重复使用和易于测试。

As a general rule, views must be small. No more than 15 lines. That makes the code readable, reusable and easy to test.

我将提供一个例子,使其更清晰,假​​设在Tastypie方法,你必须创建一个对象一样,可能发出一个信号:

I'll provide an example to make it clearer, suppose in that Tastypie method you must be creating a Like object, maybe sending a signal:

class AlbumImageResource(ModelResource):
    def like_method(self, request, **kwargs):
        # Do some method checking

        Like.objects.create(
            user=request.user,
            object=request.data.get("object")
        )
        signals.liked_object(request.user, request.data.get("object"))

        # Something more

但是,如果你需要重用的视图中的行为,正确的事情是因式分解,在不同的功能:

But, if you need to reuse that behavior in a view, the proper thing would be to factorize that in a different function:

# myapp.utils
def like_object(user, object):
    like = Like.objects.create(
        user=request.user,
        object=request.data.get("object")
    )
    signals.liked_object(request.user, request.data.get("object"))
    return like

现在你可以从你的API方法和您的视图调用它:

Now you can call it from your API method and your view:

class AlbumImageResource(ModelResource):
    def like_method(self, request, **kwargs):
        # Do some method checking
        like_object(request.user, request.data.get("object")) # Here!

而在你的视图...

And in your view...

# Your view
def test(request, object_id):
    obj = get_object_or_404(Object, id=object_id)
    like_object(request.user, obj)
    return HttpResponse() 

希望它帮助。

这篇关于使用从其它视图tastypie API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆