将Django视图中的代码重用到另一个视图

时间:2016-03-22 19:26:35

标签: python django views

所以我有一个Django(1.8.9)功能视图如下:

@api_view(['GET')]
def fruit_ranker(request):
"""
This view is responsible for generating the list of top 5
fruits based on sales
"""
****busines logic***
****busines logic***
****busines logic***
****busines logic***
....
....

然后将此特定视图绑定到urls.py中的网址,以便 http://127.0.0.1:8000/app_name/fruit-ranker 为我提供前5个水果的JSON输出。按预期工作。

现在我要求为前五种蔬菜做同样的事情,它需要有一个单独的网址,例如 http://127.0.0.1:8000/app_name/veggie-ranker 。所以我创建了以下视图来绑定到这个URL,如下:

@api_view(['GET')]
def vegetable_ranker(request):
"""
This view is responsible for generating the list of top 5
vegetables based on sales
"""

问题是业务逻辑完全相同,尽管对于SQL中的select语句,对于第一种情况,我选择水果,在第二种情况下,我选择vegetables。如何重用所有现有代码第一个视图,而不必再次重写它,并适应小的SQL更改?我可以以某种方式将第一个视图作为装饰器添加到第二个视图,以便我可以抽象所有代码并允许我灵活地进行SL更改吗?

2 个答案:

答案 0 :(得分:1)

虽然最好将两个视图分开(如果以后你想要更改一个而不是其他视图),但如果你想使用一个视图,你可以这样做。

def combined_view(request):
    if request.path == 'app_name/veggie-ranker/':
        # return top 5 vegitables
    else:
        # return top 5 fruites

或者你可以这样做:

# in urls.py
url(r'^/(?P<return_type>.+)/$')

# in views.py
def combined_view(request, return_type):
    if return_type == 'veggie-ranker':
        # return top 5 vegetables
    elif return_type == 'fruit-ranker':
        # return top 5 fruits
    else:
        raise Http404

答案 1 :(得分:0)

如果您创建了一个通用排名,例如:

def generic_ranker(request, field_or_model_name):
"""
This function is responsible for generating the list of top 5
field_or_model based on sales
"""

***business logic***
***business logic***
***business logic***
***business logic***

然后您的实际观点将是:

@api_view(['GET')]
def vegetable_ranker(request):
"""
This view is responsible for generating the list of top 5
vegetables based on sales
"""
    return generic_ranker(request, Vegetable)


@api_view(['GET')]
def fruit_ranker(request):
"""
This view is responsible for generating the list of top 5
vegetables based on sales
"""
    return generic_ranker(request, Fruit)

但是,我想知道为什么你依赖于函数视图。如果你快速看一下Class based views,你会发现你可以如此高效地完成这么多事情。