Django CBV:在同一类中创建函数

时间:2018-08-20 10:12:56

标签: django django-class-based-views

我正在基于Django Class Based View进行新项目,并且希望获得建议以分解重要的post function

我对这个概念还很陌生。

我的帖子功能如下:

def post(self, request, *args, **kwargs):
        form = self.form_class()
        query_document = None
        query_document_updated = None
        query_app = None
        query_document_count = None


    if "UpdateDocument" in request.POST:
        checkbox_id = request.POST['DocumentChoice']
        checkbox_id_minus_1 = int(checkbox_id) - 1

        query_document_updated = Document.objects.get(id=checkbox_id)

        APP_CODE = query_document_updated.app.code
        SRC_FILENAME = query_document_updated.src_filename
        FILENAME, file_extension = os.path.splitext(SRC_FILENAME)
        CATEGORY = query_document_updated.category

        if CATEGORY == "ANNUAL":
            CATEGORY = "ANNUAL_REPORT"

        # Get the new year selected by user
        year = self.request.POST.get('q1year')

        # Create the new document title updated by the new year
        new_document_title = f"{year}_{CATEGORY}_{APP_CODE}" + " - " + f"{SRC_FILENAME}"

        # Create the new document file updated by the new year
        new_document_file = "app_docs/" + f"{APP_CODE}" + "/" + \
                            f"{year}_{CATEGORY}_{APP_CODE}_{checkbox_id_minus_1}{file_extension}"

    context = {
        'form': form,
        'query_app' : query_app,
        'query_document': query_document,
        'query_document_updated': query_document_updated,
        'query_document_count' : query_document_count
    }
    return render(request, self.template_name, context)

我想创建两个新函数:new_document_titlenew_document_file并在post中调用这两个函数

我该怎么做?在post之后创建两个函数,并在参数中传递变量?

3 个答案:

答案 0 :(得分:2)

我认为您可以通过多种方式来做到!我在这里写一些,

方法1:使用class methods

from rest_framework.views import APIView


class MyView(APIView):
    def _new_document_title(self, *args, **kwargs):
        # do something
        return something

    def _new_document_file(self, *args, **kwargs):
        # do something
        return something

    def post(self, request, *args, **kwargs):
        self._new_document_title()  # calling "_new_document_title"
        self._new_document_file()  # _new_document_file
        # do something
        return some_response

方法2:使用Mixin class

class MyMixin(object):
    def new_document_title(self, *args, **kwargs):
        # do something
        return something

    def new_document_file(self, *args, **kwargs):
        # do something
        return something


class MyView(APIView, MyMixin):
    def post(self, request, *args, **kwargs):
        self.new_document_title()  # calling "new_document_title"
        self.new_document_file()  # new_document_file
        # do something
        return some_response

方法3:调用外部函数

from rest_framework.views import APIView


def new_document_title(self, *args, **kwargs):
    # do something
    return something


def new_document_file(self, *args, **kwargs):
    # do something
    return something


class MyView(APIView):

    def post(self, request, *args, **kwargs):
        new_document_title()  # calling "new_document_title"
        new_document_file()  # new_document_file
        # do something
        return some_response

答案 1 :(得分:1)

您可以在视图类本身(如果特定于该视图)中编写函数,也可以在其他一些mixin(对于其他视图而言也是通用的)中编写函数。

#!/usr/bin/python
# -*- coding: utf-8 -*-


class Mixin(object):
    def process(self, data):
        return data


class CBV(APIView, Mixin):

    def utility_function_1(self, data):
        return self.process(data)

    def utility_function_2(self, data):
        return self.process(data)

    def post(self, request, *args, **kwargs):
        processed_data = self.utility_function_1(request.data)
        processed_data = self.utility_function_2(processed_data)
        return render(request, self.template_name, {'data': processed_data})

答案 2 :(得分:1)

来自@umair的代码示例是正确的方向。

不过,如果您希望代码可以进行大规模测试和维护,则应该将辅助函数外包到另一个python文件中:

helpers.py

#!/usr/bin/python
# -*- coding: utf-8 -*-

class Helper():

    @staticmethod
    def utility_function_1(self, data):
        return process(data)

    @staticmethod
    def utility_function_2(self, data):
        return process(data)

views.py

#!/usr/bin/python
# -*- coding: utf-8 -*-

# -- adjust -- >import helpers as helper

class CBV(APIView, Mixin):

    def post(self, request, *args, **kwargs):
        processed_data = helper.utility_function_1(request.data)
        processed_data = helper.utility_function_2(processed_data)
        return render(request, self.template_name, {'data': processed_data})