python - Django 中的 DRY View

标签 python django model-view-controller dry

我构建了一个应用程序,该应用程序具有许多相似的 View ,这些 View 应该能够使用相同的基本代码。然而,每种方法在方法内的不同拐点处都有某些独特的特征,因此我无法找到一种方法来构建它以实际重用任何代码。相反,我创建了一种剪切和粘贴方法,并单独调整了每个方法。应用程序的这一部分是我编写的第一个 Python 代码,我知道一定有更好的方法来做到这一点,但我被锁定这样做并且“它有效”,所以我看不到出路.

这是基本 View 模板的本质:

def view_entity(request, entity_id=None):
    if request.method == 'POST':
        return _post_entity(request, entity_id)
    else:
        return _get_entity(request, entity_id)

def _get_entity(request, entity_id):
    data = _process_entity(request, entity_id)
    if 'redirect' in data:
        return data['redirect']
    else:
        return _render_entity(request, data['form'])

def _post_entity(request, entity_id):
    data = _process_entity(request, entity_id)
    if 'redirect' in data:
        return data['redirect']
    elif data['form'].is_valid():
        # custom post processing here
        instance = data['form'].save()
        return HttpResponseRedirect(reverse('entity', args=[instance.id]))
    else:
        return _render_entity(request, data['form'])


def _process_entity(request, entity_id):
    data = {}

    if entity_id != 'new':  # READ/UPDATE
        # sometimes there's custom code to retrieve the entity
        e = entity_id and get_object_or_404(Entity.objects, pk=entity_id)
        # sometimes there's custom code here that deauthorizes e
        # sometimes extra values are added to data here (e.g. parent entity)
        if e:
            if request.method == 'POST':
                data['form'] = EntityForm(request.POST, instance=e)
                # sometimes there's a conditional here for CustomEntityForm
            else:
                data['form'] = EntityForm(instance=e)
        else:  # user not authorized for this entity
            return {'redirect': HttpResponseRedirect(reverse('home'))}
        # sometimes there's custom code here for certain entity types

    else:  # CREATE
        if request.method == 'POST':
            data['form'] = EntityForm(request.POST)
        else:
            data['form'] = EntityForm()

    # sometimes extra key/values are added to data here
    return data

我什至没有包含所有可能的变体,但正如您所看到的,_process_entity 方法需要根据正在处理的实体类型进行大量单独的自定义。这是我无法找到一种简单的方法来处理这个问题的主要原因。

感谢任何帮助,谢谢!

最佳答案

使用基于类的 View 。您可以使用类的继承和其他功能来提高 View 的可重用性。您还可以使用内置通用 View 来简化一些基本任务。

检查class-based views documentation 。您还可以阅读此this

关于python - Django 中的 DRY View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11458424/

相关文章:

python - 将 Pandas 中的单元格值附加到行中的空单元格中

python - 如何基于数组从 (geo)pandas 数据框中选择多行或传播聚类算法结果的元数据?

Django Rest Framework 自定义端点

python - Django - 如何链接表格

django - django无法在用于指定中介模型的ManyToManyField上设置值。改用Manager

python - future 警告 : Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated

Python argparse : Is there a way to specify a range in nargs?

angularjs - 在 MVC 应用程序中将 Power Bi 报告与 Angular JS 集成

java - 如何直接从ftl模板调用FreeMarker指令?

javascript - ExtJS 4 MVC 概念的问题