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

相關文章
相關標籤/搜索