Django 在新一代的 Web框架 中非常出色
使用Python開發Web,最簡單,原始和直接的辦法是使用CGI標准,可以用WSGI接口
一、WSGI接口實現web頁面
運行WSGI服務
我們先編寫hello.py
,實現Web應用程序的WSGI處理函數:
# hello.py def application(environ, start_response): start_response('200 OK', [('Content-Type', 'text/html')]) return [b'<h1>Hello, web!</h1>']
然后,再編寫一個server.py
,負責啟動WSGI服務器,加載application()
函數:
# server.py # 從wsgiref模塊導入: from wsgiref.simple_server import make_server # 導入我們自己編寫的application函數: from hello import application # 創建一個服務器,IP地址為空,端口是8000,處理函數是application: httpd = make_server('', 8000, application) print('Serving HTTP on port 8000...') # 開始監聽HTTP請求: httpd.serve_forever()
然后在目錄下命令行輸入python server.py
來啟動WSGI服務器,瀏覽器頁面輸入127.0.0.1:8000即可訪問
這樣做的缺點就是,代碼不好重用,無法連接數據庫,頁面調樣式麻煩
從頭開始編寫網絡應用程序。
從頭編寫另一個網絡應用程序。
從第一步中總結(找出其中通用的代碼),並運用在第二步中。
重構代碼使得能在第 2 個程序中使用第 1 個程序中的通用代碼。
重復 2-4 步驟若干次。
意識到你發明了一個框架。
二、Django使用
MVC 設計模式
關鍵的4個文件(models.py , views.py , urls.py ) 和html模板文件 (template.html )
models.py 文件主要用一個 Python 類來描述數據表。 稱為 模型(model) 。 運用這個類,你可以通過簡單的 Python 的代碼來創建、檢索、更新、刪除 數據庫中的記錄而無需寫一條又一條的SQL語句。
views.py文件包含了頁面的業務邏輯。 latest_books()函數叫做視圖。
urls.py 指出了什么樣的 URL 調用什么的視圖。
template.html 是 html 模板,它描述了這個頁面的設計是如何的。
結合起來,這些部分松散遵循的模式稱為模型-視圖-控制器(MVC)。
urls.py中添加
from django.contrib import admin
from mysite1 import views
from django.conf.urls import url
urlpatterns =[
url(r'^contact/$', views.contact_result),
url(r'^contact-form/$', views.contact),]
views.py中添加
from django.http import HttpResponse, Http404
import datetime
from django.template import Template, Context
from django.shortcuts import render_to_response
from django.template.loader import get_template
from books.models import Book
from django.core.mail import send_mail
from django.http import HttpResponseRedirect
def contact(request):
errors = []
if request.method == 'POST':
if not request.POST.get('subject', ''):
errors.append('Enter a subject.')
if not request.POST.get('message', ''):
errors.append('Enter a message.')
if request.POST.get('email') and '@' not in request.POST['email']:
errors.append('Enter a valid e-mail address.')
if not errors:
send_mail(
request.POST['subject'],
request.POST['message'],
request.POST.get('email', 'noreply@example.com'),
['siteowner@example.com'],
)
return HttpResponseRedirect('/contact/thanks/')
return render_to_response('contact_form.html',
{'errors': errors})
def contact_result(request):
return render_to_response('contact.html')
template文件中添加contact.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>success</title>
</head>
<body>
finally
</body>
</html>
template文件中添加contact_form.html
<html>
<head>
<title>Contact us</title>
</head>
<body>
<h1>Contact us</h1>
{% if errors %}
<ul>
{% for error in errors %}
<li>{{ error }}</li>
{% endfor %}
</ul>
{% endif %}
<form action="/contact/" method="post">
<p>Subject: <input type="text" name="subject"></p>
<p>Your e-mail (optional): <input type="text" name="email"></p>
<p>Message: <textarea name="message" rows="10" cols="50"></textarea></p>
<input type="submit" value="Submit">
</form>
</body>
</html>
啟用服務,瀏覽器中訪問http://127.0.0.1:8000/contact/
點擊submit,跳轉到contact.html頁面