Django MVT 模型及其模块介绍

概述

最近在学习 DJango 框架,作为一个完美主义者的终极框架。虽然前面有做过一个简单的案例——DJango框架快速入门,但是对于初学者来说,往往有一种盲人摸象的感觉,尤其是像我这样做嵌入式开发而不是 Web 开发的童鞋。

在介绍一些 DJango 的常用模块之前,先来了解一下 Web 架构中最基本的 MVC 模型,以及 DJango 改良版本 MVT 模型。

简单来说:

  • MVC 即 “模型-视图-控制器”(Model View Controller)
  • MVT 即 “模型-视图-模板”(Model View Template)

MVC 模型

MVC 是一种软件设计典范,用一种业务逻辑、数据、界面显示分离的方法组织代码,将业务逻辑聚集到一个部件里面,在改进和个性化定制界面及用户交互的同时,不需要重新编写业务逻辑。

Django MVT 模型及其模块介绍_第1张图片

其中:

  • Model 用于封装对数据库层的访问,对数据库中的数据进行增、删、改、查操作;
  • View 用于封装结果,生成页面展示的 html 内容;
  • Controller 则用于接收请求,处理业务逻辑,与 Model 和 View 交互,返回结果。

这样一来,整个 “请求-响应” 过程就变得简单、清晰明了,而且前后端解耦了,便于后期扩展和工程师们的协同开发。

MVT 模型

DJango 框架遵循的模型是类似于 MVC 的 MVT,看起来只是 C 和 T 的区别,但其实 V 也有所不同。DJango 的 View 还承担了 MVC 模型中 Controller 的功能,也就是处理业务逻辑。而响应的 html 页面则由 Template 负责。

Django MVT 模型及其模块介绍_第2张图片

再来看看:

  • Model 是数据存取层,与 MVC 中的 M 功能相同,负责和数据库交互,进行数据处理;
  • View 是业务逻辑层,与 MVC 中的 C 功能类似,接收请求,进行业务处理,返回应答;(可以看作 M 和 T 之间的桥梁)
  • Template 是表现层,与 MVC 中的 V 功能类似,负责封装构造要返回的 html 页面内容。

DJango 模块

当我们了解 DJango 的 MVT 模型之后,再来看 DJango 框架所包含的一些模块就比较容易理解啦。

我们可以在 Python3 交互终端输入:

>> import django
>> help(django)

可以看到当前版本的 DJango 包含哪些模块(或者说 Package)

Help on package django:

NAME
    django

PACKAGE CONTENTS
    __main__
    apps (package)
    conf (package)
    contrib (package)
    core (package)
    db (package)
    dispatch (package)
    forms (package)
    http (package)
    middleware (package)
    shortcuts
    template (package)
    templatetags (package)
    test (package)
    urls (package)
    utils (package)
    views (package)

FUNCTIONS
    setup(set_prefix=True)
        Configure the settings (this happens as a side effect of accessing the
        first setting), configure logging and populate the app registry.
        Set the thread-local urlresolvers script prefix if `set_prefix` is True.

DATA
    VERSION = (1, 11, 11, 'final', 0)
    unicode_literals = _Feature((2, 6, 0, 'alpha', 2), (3, 0, 0, 'alpha', ...

VERSION
    1.11.11

FILE
    /usr/local/lib/python3.5/dist-packages/django/__init__.py


Django 是一个完美主义者的 Web 框架,其所涵盖的模块还是很全面的。

apps (package)

AppConfig  apps       config     registry

conf (package)

ENVIRONMENT_VARIABLE  LazySettings          empty                 locale                time
ImproperlyConfigured  Settings              global_settings       os                    urls
LazyObject            UserSettingsHolder    importlib             settings              

contrib (package)

admin         auth          flatpages     humanize      postgres      sessions      sites         syndication
admindocs     contenttypes  gis           messages      redirects     sitemaps      staticfiles   

core (package)

cache         exceptions    handlers      management    serializers   signals       urlresolvers  wsgi
checks        files         mail          paginator     servers       signing       validators    

db (package)

ConnectionHandler          Error                      backends                   router
ConnectionRouter           IntegrityError             close_old_connections      signals
DEFAULT_DB_ALIAS           InterfaceError             connection                 transaction
DJANGO_VERSION_PICKLE_KEY  InternalError              connections                utils
DataError                  NotSupportedError          migrations                 
DatabaseError              OperationalError           models                     
DefaultConnectionProxy     ProgrammingError           reset_queries              

dispatch (package)

Signal             dispatcher         receiver           weakref_backports

forms (package)

ALL_FIELDS                 EmailInput                 NullBooleanSelect          ValidationError
BaseForm                   Field                      NumberInput                Widget
BaseFormSet                FileField                  PasswordInput              all_valid
BaseInlineFormSet          FileInput                  RadioSelect                boundfield
BaseModelForm              FilePathField              RegexField                 extras
BaseModelFormSet           FloatField                 Select                     fields
BooleanField               Form                       SelectDateWidget           fields_for_model
BoundField                 GenericIPAddressField      SelectMultiple             forms
CharField                  HiddenInput                SlugField                  formset_factory
CheckboxInput              ImageField                 SplitDateTimeField         formsets
CheckboxSelectMultiple     IntegerField               SplitDateTimeWidget        inlineformset_factory
ChoiceField                Media                      SplitHiddenDateTimeWidget  model_to_dict
ClearableFileInput         MediaDefiningClass         TextInput                  modelform_factory
ComboField                 ModelChoiceField           Textarea                   modelformset_factory
DateField                  ModelForm                  TimeField                  models
DateInput                  ModelMultipleChoiceField   TimeInput                  renderers
DateTimeField              MultiValueField            TypedChoiceField           utils
DateTimeInput              MultiWidget                TypedMultipleChoiceField   widgets
DecimalField               MultipleChoiceField        URLField                   
DurationField              MultipleHiddenInput        URLInput                   
EmailField                 NullBooleanField           UUIDField                  

http (package)

BadHeaderError                 HttpResponseGone               JsonResponse                   multipartparser
FileResponse                   HttpResponseNotAllowed         QueryDict                      parse_cookie
Http404                        HttpResponseNotFound           RawPostDataException           request
HttpRequest                    HttpResponseNotModified        SimpleCookie                   response
HttpResponse                   HttpResponsePermanentRedirect  StreamingHttpResponse          
HttpResponseBadRequest         HttpResponseRedirect           UnreadablePostError            
HttpResponseForbidden          HttpResponseServerError        cookie

middleware (package)

cache         clickjacking  common        csrf          gzip          http          locale        security

shortcuts

Http404                        Promise                        loader                         reverse
HttpResponse                   _get_queryset                  redirect                       six
HttpResponsePermanentRedirect  force_text                     render                         
HttpResponseRedirect           get_list_or_404                render_to_response             
NoReverseMatch                 get_object_or_404              resolve_url

template (package)

Context               Origin                VariableDoesNotExist  engine                response
ContextPopException   RequestContext        backends              engines               smartif
Engine                StringOrigin          base                  exceptions            utils
EngineHandler         Template              context               library               
Library               TemplateDoesNotExist  context_processors    loader                
Node                  TemplateSyntaxError   defaultfilters        loader_tags           
NodeList              Variable              defaulttags           loaders

templatetags (package)

cache   i18n    l10n    static  tz

test (package)

Client                  TransactionTestCase     modify_settings         signals                 testcases
LiveServerTestCase      client                  override_settings       skipIfDBFeature         utils
RequestFactory          html                    override_system_checks  skipUnlessAnyDBFeature  
SimpleTestCase          ignore_warnings         runner                  skipUnlessDBFeature     
TestCase                mock                    selenium                tag

urls (package)

LocaleRegexProvider     ResolverMatch           get_mod_func            resolve                 translate_url
LocaleRegexURLResolver  base                    get_ns_resolver         resolvers               utils
NoReverseMatch          clear_script_prefix     get_resolver            reverse                 
RegexURLPattern         clear_url_caches        get_script_prefix       reverse_lazy            
RegexURLResolver        exceptions              get_urlconf             set_script_prefix       
Resolver404             get_callable            is_valid_path           set_urlconf

utils (package)

_os             dateformat      duration        html_parser     lorem_ipsum     synch           version
archive         dateparse       encoding        http            lru_cache       termcolors      xmlutils
autoreload      dates           feedgenerator   inspect         module_loading  text            
baseconv        datetime_safe   formats         ipv6            numberformat    timesince       
cache           deconstruct     functional      itercompat      regex_helper    timezone        
crypto          decorators      glob            jslex           safestring      translation     
datastructures  deprecation     html            log             six             tree

views (package)

View        csrf        debug       decorators  defaults    generic     i18n        static

你可能感兴趣的:(Python,全栈)