深入學習Django源碼基礎15 - views簡要分析學習

在django中,view有2種編碼形式。

1種是function返回

1種是class返回


分析

views文件夾

views
|----decorators
     |----__init__.py
     |----cache.py
     |----clickjacking.py
     |----csrf.py
     |----debug.py
     |----gzip.py
     |----http.py
     |----vary.py
|----generic
     |----__init__.py
     |----base.py
     |----dates.py
     |----detail.py
     |----edit.py
     |----list.py
|----__init__.py
|----csrf.py
|----defaults.py
|----i18n.py
|----static.py

對於views目錄和decorators目錄下的文件,主要是爲了封裝了一些函數和裝飾器,爲了方便函數返回response的代碼

對於generic目錄下的代碼。感覺寫起來很帥氣。利用多重集成實現mvc分離。把數據源獲取,模版渲染。拆分開

下面是精簡演示代碼。具體就不分析了

from functools import update_wrapper

class ContextMixin(object):
    def get_context_data(self, **kwargs):
        print 'get contenxt'
        if 'view' not in kwargs:
            kwargs['view'] = self
        return kwargs

class View(object):
    http_method_names = ['get','post','put','delete']
    def __init__(self, **kwargs):
        for (k, v) in kwargs.items():
            setattr(self, k, v)

    @classmethod
    def as_view(cls, **initkwargs):
        for key in initkwargs:
            if key in cls.http_method_names:
                raise "can't set httpmethod key"

        def view(request, *args, **kwargs):
            self = cls(**initkwargs)
            self.request = request
            self.args = args
            self.kwargs = kwargs
            return self.dispatch(request, *args, **kwargs)

        update_wrapper(view, cls, updated=())
        update_wrapper(view, cls.dispatch, updated=())

        return view

    def dispatch(self, request, *args, **kwargs):
        if request.method.lower() in self.http_method_names:
            handler = getattr(self, request.method.lower())
        else:
            raise "Can't dispatch request"
        return handler(request, *args, **kwargs)

class TemplateResponseMixin(object):
    template_name = None

    def render_to_response(self, context, **response_kwargs):
        print 'render context:[%s] to html["%s"]' % (context, self.template_name)


class TemplateView(TemplateResponseMixin, ContextMixin, View):
    def get(self, request, *args, **kwargs):
        context = self.get_context_data(**kwargs)
        return self.render_to_response(context)


class AboutView(TemplateView):
    template_name = 'about.html'

class Request(object):
    def __init__(self, method = 'get'):
        self.method = method

AboutView.as_view(template_name='1.html')(Request())

輸出內容爲:

get contenxt
render context:[{'view': <__main__.AboutView object at 0x103bd8e10>}] to html["1.html"]

發佈了104 篇原創文章 · 獲贊 8 · 訪問量 61萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章