讓咱們來研究一個簡單的例子,經過該實例,你能夠分辨出,經過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>
不用關心語法細節,只要用心感受總體的設計。 這裏只關注分割後的幾個文件:框架
小結:結合起來,這些部分鬆散遵循的模式稱爲模型-視圖-控制器(MVC)。 簡單的說, MVC是一種軟件開發的方法,它把代碼的定義和數據訪問的方法(模型)與請求邏輯 (控制器)還有用戶接口(視圖)分開來。函數
這種設計模式關鍵的優點在於各類組件都是 鬆散結合 的。這樣,每一個由 Django驅動 的Web應用都有着明確的目的,而且可獨立更改而不影響到其它的部分。 好比,開發者 更改一個應用程序中的 URL 而不用影響到這個程序底層的實現。 設計師能夠改變 HTML 頁面 的樣式而不用接觸 Python 代碼。 數據庫管理員能夠從新命名數據表而且只需更改一個地方,無需從一大堆文件中進行查找和替換。url