1. 程式人生 > >西遊之路——python全棧——Django~1 Django~1

西遊之路——python全棧——Django~1 Django~1

Django~1

 

知識預覽

一 什麼是web框架?

框架,即framework,特指為解決一個開放性問題而設計的具有一定約束性的支撐結構,使用框架可以幫你快速開發特定的系統,簡單地說,就是你用別人搭建好的舞臺來做表演。

對於所有的Web應用,本質上其實就是一個socket服務端,使用者的瀏覽器其實就是一個socket客戶端。

  View Code

      最簡單的Web應用就是先把HTML用檔案儲存好,用一個現成的HTTP伺服器軟體,接收使用者請求,從檔案中讀取HTML,返回。

如果要動態生成HTML,就需要把上述步驟自己來實現。不過,接受HTTP請求、解析HTTP請求、傳送HTTP響應都是苦力活,如果我們自己來寫這些底層程式碼,還沒開始寫動態HTML呢,就得花個把月去讀HTTP規範。

      正確的做法是底層程式碼由專門的伺服器軟體實現,我們用Python專注於生成HTML文件。因為我們不希望接觸到TCP連線、HTTP原始請求和響應格式,所以,需要一個統一的介面,讓我們專心用Python編寫Web業務。

這個介面就是WSGI:Web Server Gateway Interface。

-----------------------------Do a web  framework ourselves---------------------------

step 1:

 1 from wsgiref.simple_server import make_server
 2 
 3 
 4 def application(environ, start_response):
 5     start_response('200 OK', [('Content-Type', 'text/html')])
 6     return [b'<h1>Hello, web!</h1>']
 7 
 8 
 9 httpd = make_server('', 8080, application)
10 
11 print('Serving HTTP on port 8000...')
12 # 開始監聽HTTP請求:
13 httpd.serve_forever()
View Code

注意:

 1 整個application()函式本身沒有涉及到任何解析HTTP的部分,也就是說,底層程式碼不需要我們自己編寫,
 2 我們只負責在更高層次上考慮如何響應請求就可以了。
 3 
 4 application()函式必須由WSGI伺服器來呼叫。有很多符合WSGI規範的伺服器,我們可以挑選一個來用。
 5 
 6 Python內建了一個WSGI伺服器,這個模組叫wsgiref    
 7     
 8     
 9 application()函式就是符合WSGI標準的一個HTTP處理函式,它接收兩個引數:
10 
11         //environ:一個包含所有HTTP請求資訊的dict物件;
12         
13         //start_response:一個傳送HTTP響應的函式。
14 
15 在application()函式中,呼叫:
16 
17 start_response('200 OK', [('Content-Type', 'text/html')])
18 
19 就傳送了HTTP響應的Header,注意Header只能傳送一次,也就是隻能呼叫一次start_response()函式。
20 start_response()函式接收兩個引數,一個是HTTP響應碼,一個是一組list表示的HTTP Header,每
21 個Header用一個包含兩個str的tuple表示。
22 
23 通常情況下,都應該把Content-Type頭髮送給瀏覽器。其他很多常用的HTTP Header也應該傳送。
24 
25 然後,函式的返回值b'<h1>Hello, web!</h1>'將作為HTTP響應的Body傳送給瀏覽器。
26 
27 有了WSGI,我們關心的就是如何從environ這個dict物件拿到HTTP請求資訊,然後構造HTML,
28 通過start_response()傳送Header,最後返回Body。
View Code

step 2

 1 print(environ['PATH_INFO'])
 2     path=environ['PATH_INFO']
 3     start_response('200 OK', [('Content-Type', 'text/html')])
 4     f1=open("index1.html","rb")
 5     data1=f1.read()
 6     f2=open("index2.html","rb")
 7     data2=f2.read()
 8 
 9     if path=="/yuan":
10         return [data1]
11     elif path=="/alex":
12         return [data2]
13     else:
14         return ["<h1>404</h1>".encode('utf8')]
View Code

step3

 1 from wsgiref.simple_server import make_server
 2 
 3 def f1():
 4     f1=open("index1.html","rb")
 5     data1=f1.read()
 6     return [data1]
 7 
 8 def f2():
 9     f2=open("index2.html","rb")
10     data2=f2.read()
11     return [data2]
12 
13 def application(environ, start_response):
14 
15     print(environ['PATH_INFO'])
16     path=environ['PATH_INFO']
17     start_response('200 OK', [('Content-Type', 'text/html')])
18 
19 
20     if path=="/yuan":
21         return f1()
22 
23     elif path=="/alex":
24         return f2()
25 
26     else:
27         return ["<h1>404</h1>".encode("utf8")]
28 
29 
30 httpd = make_server('', 8502, application)
31 
32 print('Serving HTTP on port 8084...')
33 
34 # 開始監聽HTTP請求:
35 httpd.serve_forever()
View Code

step4

 1 from wsgiref.simple_server import make_server
 2 
 3 
 4 def f1(req):
 5     print(req)
 6     print(req["QUERY_STRING"])
 7 
 8     f1=open("index1.html","rb")
 9     data1=f1.read()
10     return [data1]
11 
12 def f2(req):
13 
14     f2=open("index2.html","rb")
15     data2=f2.read()
16     return [data2]
17 
18 import time
19 
20 def f3(req):        #模版以及資料庫
21 
22     f3=open("index3.html","rb")
23     data3=f3.read()
24     times=time.strftime("%Y-%m-%d %X", time.localtime())
25     data3=str(data3,"utf8").replace("!time!",str(times))
26 
27 
28     return [data3.encode("utf8")]
29 
30 
31 def routers():
32 
33     urlpatterns = (
34         ('/yuan',f1),
35         ('/alex',f2),
36         ("/cur_time",f3)
37     )
38     return urlpatterns
39 
40 
41 def application(environ, start_response):
42 
43     print(environ['PATH_INFO'])
44     path=environ['PATH_INFO']
45     start_response('200 OK', [('Content-Type', 'text/html')])
46 
47 
48     urlpatterns = routers()
49     func = None
50     for item in urlpatterns:
51         if item[0] == path:
52             func = item[1]
53             break
54     if func:
55         return func(environ)
56     else:
57         return ["<h1>404</h1>".encode("utf8")]
58 
59 httpd = make_server('', 8518, application)
60 
61 print('Serving HTTP on port 8084...')
62 
63 # 開始監聽HTTP請求:
64 
65 httpd.serve_forever()
View Code

夥計們,不知不覺我們自己已經寫出一個web框架啦!

二 MVC和MTV模式

著名的MVC模式:所謂MVC就是把web應用分為模型(M),控制器(C),檢視(V)三層;他們之間以一種外掛似的,鬆耦合的方式連線在一起。

模型負責業務物件與資料庫的物件(ORM),檢視負責與使用者的互動(頁面),控制器(C)接受使用者的輸入呼叫模型和檢視完成使用者的請求。

                   

Django的MTV模式本質上與MVC模式沒有什麼差別,也是各元件之間為了保持鬆耦合關係,只是定義上有些許不同,Django的MTV分別代表:

       Model(模型):負責業務物件與資料庫的物件(ORM)

       Template(模版):負責如何把頁面展示給使用者

       View(檢視):負責業務邏輯,並在適當的時候呼叫Model和Template

       此外,Django還有一個url分發器,它的作用是將一個個URL的頁面請求分發給不同的view處理,view再呼叫相應的Model和Template

 三 django的流程和命令列工具

django實現流程

 1 django
 2     #安裝: pip3 install django
 3 
 4           新增環境變數
 5 
 6     #1  建立project
 7        django-admin startproject mysite
 8 
 9        ---mysite
10 
11           ---settings.py
12           ---url.py
13           ---wsgi.py
14 
15        ---- manage.py(啟動檔案)  
16 
17     #2  建立APP       
18        python mannage.py startapp  app01
19 
20     #3  settings配置
21     
22        TEMPLATES
23 
24        STATICFILES_DIRS=(
25             os.path.join(BASE_DIR,"statics"),
26         )
27 
28        STATIC_URL = '/static/' 
29        #  我們只能用 STATIC_URL,但STATIC_URL會按著你的STATICFILES_DIRS去找#4  根據需求設計程式碼
30            url.py
31            view.py
32 
33     #5  使用模版
34        render(req,"index.html")   
35 
36     #6  啟動專案
37        python manage.py runserver  127.0.0.1:8090
38 
39     #7  連線資料庫,操作資料
40        model.py
View Code

django的命令列工具

django-admin.py 是Django的一個用於管理任務的命令列工具,manage.py是對django-admin.py的簡單包裝,每一個Django Project裡都會有一個mannage.py。

<1> 建立一個django工程 : django-admin.py startproject mysite

        當前目錄下會生成mysite的工程,目錄結構如下:

        

  • manage.py ----- Django專案裡面的工具,通過它可以呼叫django shell和資料庫等。
  • settings.py ---- 包含了專案的預設設定,包括資料庫資訊,除錯標誌以及其他一些工作的變數。
  • urls.py ----- 負責把URL模式對映到應用程式。

<2>在mysite目錄下建立blog應用: python manage.py startapp blog

        

<3>啟動django專案:python manage.py runserver 8080

       這樣我們的django就啟動起來了!當我們訪問:http://127.0.0.1:8080/時就可以看到:

       

<4>生成同步資料庫的指令碼:python manage.py makemigrations  

                     同步資料庫:  python manage.py migrate   

       注意:在開發過程中,資料庫同步誤操作之後,難免會遇到後面不能同步成功的情況,解決這個問題的一個簡單粗暴方法是把migrations目錄下

                的指令碼(除__init__.py之外)全部刪掉,再把資料庫刪掉之後建立一個新的資料庫,資料庫同步操作再重新做一遍。            

<5>當我們訪問http://127.0.0.1:8080/admin/時,會出現:

       

       所以我們需要為進入這個專案的後臺建立超級管理員:python manage.py createsuperuser設定好使用者名稱和密碼後便可登入啦!

<6>清空資料庫:python manage.py  flush

<7>查詢某個命令的詳細資訊: django-admin.py  help  startapp

       admin 是Django 自帶的一個後臺資料庫管理系統。

<8>啟動互動介面 :python manage.py  shell

     這個命令和直接執行 python 進入 shell 的區別是:你可以在這個 shell 裡面呼叫當前專案的 models.py 中的 API,對於操作資料,還有一些小測試非常方便。

<9> 終端上輸入python manage.py 可以看到詳細的列表,在忘記子名稱的時候特別有用

例項練習1-提交資料並展示

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Title</title>
 6 </head>
 7 <body>
 8 <h1>建立個人資訊</h1>
 9 
10 <form action="/userInfor/" method="post">
11 
12     <p>姓名<input type="text" name="username"></p>
13     <p>性別<input type="text" name="sex"></p>
14     <p>郵箱<input type="text" name="email"></p>
15     <p><input type="submit" value="submit"></p>
16 
17 </form>
18 
19 <hr>
20 
21 <h1>資訊展示</h1>
22 
23 <table border="1">
24 
25     <tr>
26         <td>姓名</td>
27         <td>性別</td>
28         <td>郵箱</td>
29     </tr>
30     {% for i in info_list %}
31 
32         <tr>
33             <td>{{ i.username }}</td>
34             <td>{{ i.sex }}</td>
35             <td>{{ i.email }}</td>
36         </tr>
37 
38     {% endfor %}
39 
40 </table>
41 
42 </body>
43 </html>
44 
45 
46 -----------------------url.py---------------------------------------
47 url(r'^userInfor/', views.userInfor)
48 
49 -----------------------views.py--------------------------------------
50 
51 info_list=[]
52 
53 def userInfor(req):
54 
55     if req.method=="POST":
56         username=req.POST.get("username",None)
57         sex=req.POST.get("sex",None)
58         email=req.POST.get("email",None)
59 
60         info={"username":username,"sex":sex,"email":email}
61         info_list.append(info)
62 
63     return render(req,"userInfor.html",{"info_list":info_list})
View Code

例項練習2-提交資料並展示(資料庫)

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Title</title>
 6 </head>
 7 <body>
 8 <h1>建立個人資訊</h1>
 9 
10 <form action="/userInfor/" method="post">
11 
12     <p>姓名<input type="text" name="username"></p>
13     <p>性別<input type="text" name="sex"></p>
14     <p>郵箱<input type="text" name="email"></p>
15     <p><input type="submit" value="submit"></p>
16 
17 </form>
18 
19 <hr>
20 
21 <h1>資訊展示</h1>
22 
23 <table border="1">
24 
25     <tr>
26         <td>姓名</td>
27         <td>性別</td>
28         <td>郵箱</td>
29     </tr>
30     {% for i in info_list %}
31 
32         <tr>
33             <td>{{ i.username }}</td>
34             <td>{{ i.sex }}</td>
35             <td>{{ i.email }}</td>
36         </tr>
37 
38     {% endfor %}
39 
40 </table>
41 
42 </body>
43 </html>
44 
45 
46 ----------------------------------------------models.py
47 from django.db import models
48 
49 # Create your models here.
50 
51 
52 class UserInfor(models.Model):
53 
54     username=models.CharField(max_length=64)
55     sex=models.CharField(max_length=64)
56     email=models.CharField(max_length=64)
57 
58 ----------------------------------------------views.py
59 
60 from django.shortcuts import render
61 
62 from app01 import models
63 # Create your views here.
64 
65 
66 def userInfor(req):
67 
68     if req.method=="POST":
69         u=req.POST.get("username",None)
70         s=req.POST.get("sex",None)
71         e=req.POST.get("email",None)
72 
73 
74        #---------表中插入資料方式一
75             # info={"username":u,"sex":e,"email":e}
76             # models.UserInfor.objects.create(**info)
77 
78        #---------表中插入資料方式二
79         models.UserInfor.objects.create(
80             username=u,
81             sex=s,
82             email=e
83         )
84 
85         info_list=models.UserInfor.objects.all()
86 
87         return render(req,"userInfor.html",{"info_list":info_list})
88 
89     return render(req,"userInfor.html")
View Code

四 Django的配置檔案(settings)

靜態檔案設定:

  1 一、概述:
  2 
  3      #靜態檔案交由Web伺服器處理,Django本身不處理靜態檔案。簡單的處理邏輯如下(以nginx為例):
  4 
  5      #          URI請求-----> 按照Web伺服器裡面的配置規則先處理,以nginx為例,主要求配置在nginx.
  6                              #conf裡的location
  7 
  8                          |---------->如果是靜態檔案,則由nginx直接處理
  9 
 10                          |---------->如果不是則交由Django處理,Django根據urls.py裡面的規則進行匹配
 11 
 12     # 以上是部署到Web伺服器後的處理方式,為了便於開發,Django提供了在開發環境的對靜態檔案的處理機制,方法是這樣:
 13 
 14     #1、在INSTALLED_APPS裡面加入'django.contrib.staticfiles',
 15 
 16     #2、在urls.py裡面加入
 17        if settings.DEBUG:  
 18            urlpatterns += patterns('', url(r'^media/(?P<path>.*)$', 
 19            'django.views.static.serve', {'document_root': settings.MEDIA_ROOT }),   
 20             url(r'^static/(?P<path>.*)$',
 21           'django.views.static.serve',{'document_root':settings.STATIC_ROOT}), )  
 22 
 23     # 3、這樣就可以在開發階段直接使用靜態檔案了。
 24 
 25 二、MEDIA_ROOT和MEDIA_URL
 26 
 27         #而靜態檔案的處理又包括STATIC和MEDIA兩類,這往往容易混淆,在Django裡面是這樣定義的:
 28 
 29         #MEDIA:指使用者上傳的檔案,比如在Model裡面的FileFIeld,ImageField上傳的檔案。如果你定義
 30 
 31         #MEDIA_ROOT=c:\temp\media,那麼File=models.FileField(upload_to="abc/")#,上傳的檔案就會被儲存到c:\temp\media\abc  
 32         #eg:
 33             class blog(models.Model):  
 34                    Title=models.charField(max_length=64)  
 35                    Photo=models.ImageField(upload_to="photo") 
 36         #     上傳的圖片就上傳到c:\temp\media\photo,而在模板中要顯示該檔案,則在這樣寫
 37         #在settings裡面設定的MEDIA_ROOT必須是本地路徑的絕對路徑,一般是這樣寫:
 38                  BASE_DIR= os.path.abspath(os.path.dirname(__file__))  
 39                  MEDIA_ROOT=os.path.join(BASE_DIR,'media/').replace('\\','/') 
 40 
 41         #MEDIA_URL是指從瀏覽器訪問時的地址字首,舉個例子:
 42             MEDIA_ROOT=c:\temp\media\photo  
 43             MEDIA_URL="/data/"
 44         #在開發階段,media的處理由django處理:
 45 
 46         #    訪問http://localhost/data/abc/a.png就是訪問c:\temp\media\photo\abc\a.png
 47 
 48         #    在模板裡面這樣寫<img src="{{MEDIA_URL}}abc/a.png">
 49 
 50         #    在部署階段最大的不同在於你必須讓web伺服器來處理media檔案,因此你必須在web伺服器中配置,
 51         #  以便能讓web伺服器能訪問media檔案
 52         #    以nginx為例,可以在nginx.conf裡面這樣:
 53 
 54                  location ~/media/{
 55                        root/temp/
 56                        break;
 57                     }
 58 
 59         #    具體可以參考如何在nginx部署django的資料。
 60 
 61 三、STATIC_ROOT和STATIC_URL、
 62     STATIC主要指的是如css,js,images這樣檔案,在settings裡面可以配置STATIC_ROOT和STATIC_URL,
 63     配置方式與MEDIA_ROOT是一樣的,但是要注意
 64 
 65     #STATIC檔案一般儲存在以下位置:
 66 
 67     #1、STATIC_ROOT:在settings裡面設定,一般用來放一些公共的js,css,images等。
 68 
 69     #2、app的static資料夾,在每個app所在文夾均可以建立一個static資料夾,然後當執行collectstatic時,
 70     #    Django會遍歷INSTALL_APPS裡面所有app的static資料夾,將裡面所有的檔案複製到STATIC_ROOT。因此,
 71     #   如果你要建立可複用的app,那麼你要將該app所需要的靜態檔案放在static資料夾中。
 72 
 73     # 也就是說一個專案引用了很多app,那麼這個專案所需要的css,images等靜態檔案是分散在各個app的static檔案的,比
 74     #  較典型的是admin應用。當你要釋出時,需要將這些分散的static檔案收集到一個地方就是STATIC_ROOT。
 75 
 76     #3、STATIC檔案還可以配置STATICFILES_DIRS,指定額外的靜態檔案儲存位置。
 77     #  STATIC_URL的含義與MEDIA_URL類似。
 78 
 79     # ----------------------------------------------------------------------------
 80     #注意1:
 81         #為了後端的更改不會影響前端的引入,避免造成前端大量修改
 82 
 83         STATIC_URL = '/static/'               #引用名
 84         STATICFILES_DIRS = (
 85             os.path.join(BASE_DIR,"statics")  #實際名 ,即實際資料夾的名字
 86         )
 87 
 88         #django對引用名和實際名進行對映,引用時,只能按照引用名來,不能按實際名去找
 89         #<script src="/statics/jquery-3.1.1.js"></script>
 90         #------error-----不能直接用,必須用STATIC_URL = '/static/':
 91         #<script src="/static/jquery-3.1.1.js"></script>
 92 
 93     #注意2(statics資料夾寫在不同的app下,靜態檔案的呼叫):
 94 
 95         STATIC_URL = '/static/'
 96 
 97         STATICFILES_DIRS=(
 98             ('hello',os.path.join(BASE_DIR,"app01","statics")) ,
 99         )
100 
101         #<script src="/static/hello/jquery-1.8.2.min.js"></script>
102 
103     #注意3:
104         STATIC_URL = '/static/'
105         {% load staticfiles %}
106        # <script src={% static "jquery-1.8.2.min.js" %}></script>
View Code

其它重要引數設定:

APPEND_SLASH
       Default: True
       When set to True, if the request URL does not match any of the patterns in the URLconf and it 
doesn’t end in a slash, an HTTP redirect is issued to the same URL with a slash appended. Note
that the redirect may cause any data submitted in a POST request to be lost.

五 Django URL (路由系統)

     URL配置(URLconf)就像Django 所支撐網站的目錄。它的本質是URL模式以及要為該URL模式呼叫的檢視函式之間的對映表;你就是以這種方式告訴Django,對於這個URL呼叫這段程式碼,對於那個URL呼叫那段程式碼。

1 2 3 urlpatterns = [      url(正則表示式, views檢視函式,引數,別名), ]

引數說明:

  • 一個正則表示式字串
  • 一個可呼叫物件,通常為一個檢視函式或一個指定檢視函式路徑的字串
  • 可選的要傳遞給檢視函式的預設引數(字典形式)
  • 一個可選的name引數

5.1 Here’s a sample URLconf:

複製程式碼
from django.conf.urls import url
from django.contrib import admin

from app01 import views

urlpatterns = [

    url(r'^articles/2003/$', views.special_case_2003),

    #url(r'^articles/[0-9]{4}/$', views.year_archive),

    url(r'^articles/([0-9]{4})/$', views.year_archive),  #no_named group

    url(r'^articles/([0-9]{4})/([0-9]{2})/$', views.month_archive),

    url(r'^articles/([0-9]{4})/([0-9]{2})/([0-9]+)/$', views.article_detail),

]
複製程式碼

Note:

 1 #1   There’s no need to add a leading slash, because every URL has that. For
 2 #    example, it’s ^articles, not ^/articles.
 3 
 4 #2   A request to /articles/2005/03/ would match the third entry in the list.
 5 #    Django would call the function views.month_archive(request, '2005', '03').
 6 
 7 #3   /articles/2005/3/ would not match any URL patterns
 8 
 9 #4   /articles/2003/ would match the first pattern in the list, not the second one
10 
11 #5   /articles/2003/03/03/ would match the final pattern. Django would call the
12 #    functionviews.article_detail(request, '2003', '03', '03').
View Code

 

5.2 Named groups

      The above example used simple, non-named regular-expression groups (via parenthesis) to capture bits of the URL and pass them as positional arguments to a view. In more advanced usage, it’s possible to use named regular-expression groups to capture URL bits and pass them as keyword arguments to a view.

       In Python regular expressions, the syntax for named regular-expression groups is (?P<name>pattern), where name is the name of the group and pattern is some pattern to match.

Here’s the above example URLconf, rewritten to use named groups:

1 import re
2 
3 ret=re.search('(?P<id>\d{3})/(?P<name>\w{3})','weeew34ttt123/ooo')
4 
5 print(ret.group())
6 print(ret.group('id'))
7 print(ret.group('name'))
8 
9 ready
ready

==============

複製程式碼
from django.conf.urls import url
  
from . import views
  
urlpatterns = [
    url(r'^articles/2003/$', views.special_case_2003),
    url(r'^articles/(?P<year>[0-9]{4})/$', views.year_archive),
    url(r'^articles/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/$', views.month_archive),
    url(r'^articles/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/(?P<day>[0-9]{2})/$', views.article_detail),
]
複製程式碼

       This accomplishes exactly the same thing as the previous example, with one subtle difference: The captured values are passed to view functions as keyword arguments rather than positional arguments.

5.3  Passing extra options to view functions

       URLconfs have a hook that lets you pass extra arguments to your view functions, as a Python dictionary.

The django.conf.urls.url() function can take an optional third argument which should be a dictionary of extra keyword arguments to pass to the view function.

For example:

from django.conf.urls import url
from . import views
  
urlpatterns = [
    url(r'^blog/(?P<year>[0-9]{4})/$', views.year_archive, {'foo': 'bar'}),
]

       In this example, for a request to /blog/2005/, Django will call views.year_archive(request, year='2005',foo='bar').

This technique is used in the syndication framework to pass metadata and options to views.

Dealing with conflicts

       It’s possible to have a URL pattern which captures named keyword arguments, and also passes arguments with the same names in its dictionary of extra arguments. When this happens, the arguments in the dictionary will be used instead of the arguments captured in the URL.

5.4 name param

 1 urlpatterns = [
 2     url(r'^index',views.index,name='bieming'),
 3     url(r'^admin/', admin.site.urls),
 4     # url(r'^articles/2003/$', views.special_case_2003),
 5     url(r'^articles/([0-9]{4})/$', views.year_archive),
 6     # url(r'^articles/([0-9]{4})/([0-9]{2})/$', views.month_archive),
 7     # url(r'^articles/([0-9]{4})/([0-9]{2})/([0-9]+)/$', views.article_detail),
 8 
 9 ]
10 ###################
11 
12 def index(req):
13     if req.method=='POST':
14         username=req.POST.get('username')
15         password=req.POST.get('password')
16         if username=='alex' and password=='123':
17             return HttpResponse("登陸成功")
18 
19 
20 
21     return render(req,'index.html')
22 
23 #####################
24 
25 <!DOCTYPE html>
26 <html lang="en">
27 <head>
28     <meta charset="UTF-8">
29     <title>Title</title>
30 </head>
31 <body>
32 {#     <form action="/index/" method="post">#}
33      <form action="{% url 'bieming' %}" method="post">
34          使用者名稱:<input type="text" name="username">
35          密碼:<input type="password" name="password">
36          <input type="submit" value="submit">
37      </form>
38 </body>
39 </html>
40 
41 
42 #######################
View Code

5.5 Including other URLconfs

複製程式碼
#At any point, your urlpatterns can “include” other URLconf modules. This
#essentially “roots” a set of URLs below other ones.

#For example, here’s an excerpt of the URLconf for the Django website itself.
#It includes a number of other URLconfs:


from django.conf.urls import include, url

urlpatterns = [
   url(r'^admin/', admin.site.urls),
   url(r'^blog/', include('blog.urls')),
]
複製程式碼

六 Django Views(檢視函式)

http請求中產生兩個核心物件:

        http請求:HttpRequest物件

        http響應:HttpResponse物件

所在位置:django.http

之前我們用到的引數request就是HttpRequest    檢測方法:isinstance(request,HttpRequest)

1 HttpRequest物件的屬性和方法:

 1 # path:       請求頁面的全路徑,不包括域名
 2 #
 3 # method:     請求中使用的HTTP方法的字串表示。全大寫表示。例如
 4 #
 5 #                    if  req.met