使用其他视图中的tastypie api [英] Using tastypie api from other views

查看:24
本文介绍了使用其他视图中的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)

在视图中使用美味派资源
从另一个视图调用我服务器上的 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 方法中做重要的事情.将其重构为具有通用功能.

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 行.这使代码可读、可重用且易于测试.

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

我将提供一个示例以使其更清楚,假设在该 Tastypie 方法中您必须创建一个 Like 对象,可能会发送一个信号:

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!

在你看来...

# 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天全站免登陆