MVC其实很简单(Django框架)

 

Django框架MVC其实很简单

让咱们来研究一个简单的例子,经过该实例,你能够分辨出,经过Web框架来实现的功能与以前的方式有何不一样。 下面就是经过使用Django来完成以上功能的例子: 首先,咱们分红4个Python的文件,(models.py , views.py , urls.py ) 和html模板文件 (latest_books.html )。html

models.py:python

# models.py (the database tables)

from django.db import models

class Book(models.Model):
    name = models.CharField(max_length=50)
    pub_date = models.DateField()

  

views.py (the business logic)数据库

# views.py (the business logic)

from django.shortcuts import render_to_response
from models import Book

def latest_books(request):
    book_list = Book.objects.order_by('-pub_date')[:10]
    return render_to_response('latest_books.html', {'book_list': book_list})

  

urls.py (the URL configuration)django

# urls.py (the URL configuration)

from django.conf.urls.defaults import *
import views

urlpatterns = patterns('',
    (r'^latest/$', views.latest_books),
)

  

latest_books.html (the template)设计模式

# latest_books.html (the template)

<html><head><title>Books</title></head>
<body>
<h1>Books</h1>
<ul>
{% for book in book_list %}
<li>{{ book.name }}</li>
{% endfor %}
</ul>
</body></html>

  

不用关心语法细节,只要用心感受总体的设计。 这里只关注分割后的几个文件:框架

  • models.py 文件主要用一个 Python 类来描述数据表。 称为 模型(model) 。 运用这个类,你能够经过简单的 Python 的代码来建立、检索、更新、删除 数据库中的记录而无需写一条又一条的SQL语句。
  • views.py文件包含了页面的业务逻辑。 latest_books()函数叫作视图。
  • urls.py 指出了什么样的 URL 调用什么的视图。 在这个例子中 /latest/ URL 将会调用 latest_books() 这个函数。 换句话说,若是你的域名是example.com,任何人浏览网址http://example.com/latest/将会调用latest_books()这个函数。
  • latest_books.html 是 html 模板,它描述了这个页面的设计是如何的。 使用带基本逻辑声明的模板语言,如{% for book in book_list %}

 

小结:结合起来,这些部分松散遵循的模式称为模型-视图-控制器(MVC)。 简单的说, MVC是一种软件开发的方法,它把代码的定义和数据访问的方法(模型)与请求逻辑 (控制器)还有用户接口(视图)分开来。函数

 

这种设计模式关键的优点在于各类组件都是 松散结合 的。这样,每一个由 Django驱动 的Web应用都有着明确的目的,而且可独立更改而不影响到其它的部分。 好比,开发者 更改一个应用程序中的 URL 而不用影响到这个程序底层的实现。 设计师能够改变 HTML 页面 的样式而不用接触 Python 代码。 数据库管理员能够从新命名数据表而且只需更改一个地方,无需从一大堆文件中进行查找和替换。url

相关文章
相关标签/搜索