Django Book 學習筆記(上)

拜讀了網上的Django Book,如今來總結一下吧。。。。。。php

一.Django的配置

       很是的蛋疼,因爲Django的塊組之間耦合度低,這既是它的優勢,也是它的缺點。我在Ubuntu所配置的Django的開發環境是:Django1.6+PostgreSQL+Nginx+uwsgi+Memcached(緩存機制)。配置起來確實麻煩,但不得不說Nginx的反向代理真的很是好用,uwsgi做爲Django和Nginx之間的橋樑。html

       想知道怎麼配置本身上網查吧。這裏很少說了。python

二.Django的幾條重要的命令

>>>python manage.py shell  #啓動交互界面
>>>python setup.py install  #安裝Django
$:django-admin.py startproject mysite   #新建一個web項目
>>>python manage.py runserver 端口號 #啓動Django自帶的服務器
$:uwsgi -s :端口號 -w run_uwsgi(配置文件)  
>>>python manage.py startapp books   #新建一個APP
>>>python manage.py syncdb   #打印sql語句

三.視圖與URL設置

hello 的demo:web

from django.http import HttpResponse

def hello(request):
    return HttpResponse("Hello world")

同時在urls.py做出相應的配置:正則表達式

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

urlpatterns = patterns('',
    ('^hello/$', hello),
)

附錄一下Django要用到的正則符號吧(不過仍是本身先學一下正則表達式比較好):sql

符號 匹配
. (dot) 任意單一字符
\d 任意一位數字
[A-Z] AZ中任意一個字符(大寫)
[a-z] az中任意一個字符(小寫)
[A-Za-z] az中任意一個字符(不區分大小寫)
+ 匹配一個或更多 (例如, \d+ 匹配一個或 多個數字字符)
[^/]+ 一個或多個不爲‘/’的字符
* 零個或一個以前的表達式(例如:\d? 匹配零個或一個數字)
* 匹配0個或更多 (例如, \d* 匹配0個 或更多數字字符)
{1,3} 介於一個和三個(包含)以前的表達式(例如,\d{1,3}匹配一個或兩個或三個數字)

Django中請求視圖(request)與響應視圖(response)的過程大抵是這樣:shell

  1. 進來的請求轉入/hello/.數據庫

  1. Django經過在ROOT_URLCONF配置來決定根URLconf.django

  1. Django在URLconf中的全部URL模式中,查找第一個匹配/hello/的條目。canvas

  1. 若是找到匹配,將調用相應的視圖函數

  1. 視圖函數返回一個HttpResponse

   6.Django轉換HttpResponse爲一個適合的HTTP response, 以Web page顯示出來

 

四.模板

模板的調用並不複雜,可是關於模板的標籤的內容有點多,這部分估計仍是要看一下Django Book

下面給出一個有用到模板繼承以及最精簡調用試圖的demo:

Bash.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="en">
<head>
    <title>{% block title %}{% endblock %}</title>
</head>
<body>
    <h1>My helpful timestamp site</h1>
    {% block content %}{% endblock %}
    {% block footer %}
    <hr>
    <p>Thanks for visiting my site.</p>
    {% endblock %}
</body>
</html>
current_datetime.html
{% extends "base.html" %}

{% block title %}The current time{% endblock %}

{% block content %}
<p>It is now {{ current_date }}.</p>
{% endblock %}
#views.py中的current_datetime函數
from django.shortcuts import render_to_response
import datetime

def current_datetime(request):
    now = datetime.datetime.now()
    return render_to_response('current_datetime.html', {'current_date': now})

 

五.模型

在將模型以前,先介紹一下Django不一樣於其餘MVC框架的一種另外的思想:MTV思想。

Django 牢牢地遵循這種 MVC 模式,能夠稱得上是一種 MVC 框架。 如下是 Django 中 M、V 和 C 各自的含義:

  • M ,數據存取部分,由django數據庫層處理,本章要講述的內容。

  • V ,選擇顯示哪些數據要顯示以及怎樣顯示的部分,由視圖和模板處理。

  • C ,根據用戶輸入委派視圖的部分,由 Django 框架根據 URLconf 設置,對給定 URL 調用適當的 Python 函數。

因爲 C 由框架自行處理,而 Django 裏更關注的是模型(Model)、模板(Template)和視圖(Views),Django 也被稱爲 MTV 框架 。在 MTV 開發模式中:

  • M 表明模型(Model),即數據存取層。 該層處理與數據相關的全部事務: 如何存取、如何驗證有效性、包含哪些行爲以及數據之間的關係等。

  • T 表明模板(Template),即表現層。 該層處理與表現相關的決定: 如何在頁面或其餘類型文檔中進行顯示。

  • V 表明視圖(View),即業務邏輯層。 該層包含存取模型及調取恰當模板的相關邏輯。 你能夠把它看做模型與模板之間的橋樑。

若是你熟悉其它的 MVC Web開發框架,比方說 Ruby on Rails,你可能會認爲 Django 視圖是控制器,而 Django 模板是視圖。 很不幸,這是對 MVC 不一樣詮釋所引發的錯誤認識。 在 Django 對 MVC 的詮釋中,視圖用來描述要展示給用戶的數據;不是數據 如何展示 ,並且展示 哪些 數據。 相比之下,Ruby on Rails 及一些同類框架提倡控制器負責決定向用戶展示哪些數據,而視圖則僅決定 如何 展示數據,而不是展示 哪些 數據。

兩種詮釋中沒有哪一個更加正確一些。 重要的是要理解底層概念。

模型的內容有不少,仍是本身看一下書吧。

六.管理

Django有本身的管理數據庫的模塊,相似與php的phpmyadmin。

 

七.表單

GET方法的demo:

def search(request):
    error = False
    if 'q' in request.GET:
        q = request.GET['q']
        if not q:
            error = True
        else:
            books = Book.objects.filter(title__icontains=q)
            return render_to_response('search_results.html',
                {'books': books, 'query': q})
    return render_to_response('search_form.html',
        {'error': error})

POST方法的demo:

from django.core.mail import send_mail
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response

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})

記得:對於成功的GET請求,咱們應使用render_to_response返回;而對於成功的POST請求,咱們應用HttpResponseRedirect作重定向,這是web開發的最佳實踐。

 八.輸出非html內容

視圖與MIME類型:

視圖函數只是一個以Web請求爲參數並返回Web響應的Python函數。這個響應能夠是一個Web頁面的HTML內容,或者一個跳轉,或者一個404錯誤,或者一個XML文檔,或者一幅圖片,或者映射到任何東西上。

輸出png圖像:

from django.http import HttpResponse

def my_image(request):
    image_data = open('/home/dzhwen/swift.jpg')
    return HttpResponse(image_data,mimetype="image/png")

輸出CSV文件:

import csv
from django.http import HttpResponse

# Number of unruly passengers each year 1995 - 2005. In a real application
# this would likely come from a database or some other back-end data store.
UNRULY_PASSENGERS = [146,184,235,200,226,251,299,273,281,304,203]

def unruly_passengers_csv(request):
    # Create the HttpResponse object with the appropriate CSV header.
    response = HttpResponse(mimetype='text/csv')
    response['Content-Disposition'] = 'attachment; filename=unruly.csv'

    # Create the CSV writer using the HttpResponse as the "file."
    writer = csv.writer(response)
    writer.writerow(['Year', 'Unruly Airline Passengers'])
    for (year, num) in zip(range(1995, 2006), UNRULY_PASSENGERS):
        writer.writerow([year, num])

    return response

輸出pdf文件:

from cStringIO import StringIO
from reportlab.pdfgen import canvas
from django.http import HttpResponse

def hello_pdf(request):
    response = HttpResponse(mimetype='application/pdf')
    response['Content-Disposition'] = 'attachment; filename=hello.pdf'

    temp = StringIO()
    p = canvas.Canvas(temp)

    p.drawString(100,100,"Hello world.")
    p.showPage()
    p.save()

    return response

九.會話,用戶和註冊

好壞參半的Cookies

也許你已經注意到了,cookies的工做方式可能致使的問題。 讓咱們看一下其中一些比較重要的問題:

  • cookie的存儲是自願的,一個客戶端不必定要去接受或存儲cookie。 事實上,全部的瀏覽器都讓用戶本身控制 是否接受cookies。 若是你想知道cookies對於Web應用有多重要,你能夠試着打開這個瀏覽器的 選項:

 

  • 儘管cookies廣爲使用,但仍被認爲是不可靠的的。 這意味着,開發者使用cookies以前必須 檢查用戶是否能夠接收cookie。

 

  • Cookie(特別是那些沒經過HTTPS傳輸的)是很是不安全的。 由於HTTP數據是以明文發送的,因此 特別容易受到嗅探攻擊。 也就是說,嗅探攻擊者能夠在網絡中攔截並讀取cookies,所以你要 絕對避免在cookies中存儲敏感信息。 這就意味着您不該該使用cookie來在存儲任何敏感信息。

 

  • 還有一種被稱爲」中間人」的攻擊更陰險,攻擊者攔截一個cookie並將其用於另外一個用戶。 第19章將深刻討論這種攻擊的本質以及如何避免。

 

  • 即便從預想中的接收者返回的cookie也是不安全的。 在大多數瀏覽器中您能夠很是容易地修改cookies中的信息。有經驗的用戶甚至能夠經過像mechanize(http://wwwsearch.sourceforge.net/mechanize/) 這樣的工具手工構造一個HTTP請求。

 

  • 所以不能在cookies中存儲可能會被篡改的敏感數據。 在cookies中存儲 IsLoggedIn=1 ,以標識用戶已經登陸。 犯這類錯誤的站點數量多的使人難以置信; 繞過這些網站的安全系統也是易如反掌。
相關文章
相關標籤/搜索