準備環境
1、安裝Django
$ pip install django==2.2.0
$ pip list
Package Version
---------------- -------
backcall 0.1.0
decorator 4.4.0
Django 2.2
$ python -m django --version
2.2
2、安裝 mysqlclient
$ pip3 install mysqlclient
如果報錯,請參考:https://blog.51cto.com/qiangsh/2422115
web架構的設計邏輯
1:使用者打開一個網址的步驟
從使用者角度分析一個架構(網站)都需要那些零件
經典的MVC(MTV)架構是怎麼來的呢?
- 使用者輸入網址是哪裡定義的呢?——URL
- 使用者兩種通路模式讀(get)/寫(post),誰來處理?——view(control)
- view處理的需要資料在哪存着的呢?——model
- view處理完畢,使用者請求看到的頁面是誰渲染的呢?——template(view)
2:以此設計邏輯分析django架構
首先建立django項目,檢視下項目的目錄結構
使用 django-admin 來建立 devops 項目:
django-admin.py startproject devops
檢視項目的目錄結構:
$ tree devops/
├── devops
│ ├── __init__.py
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
├── manage.py
目錄說明:
- devops: 項目的容器。
- manage.py: 一個實用的指令行工具,可讓你以各種方式與該 Django 項目進行互動。
- devops/init.py: 一個空檔案,告訴 Python 該目錄是一個 Python 包。
- devops/settings.py: 該 Django 項目的設定/配置。
- devops/urls.py: 該 Django 項目的 URL 聲明; 一份由 Django 驅動的網站"目錄"。
- devops/wsgi.py: 一個 WSGI 相容的 Web 伺服器的入口,以便運作你的項目。
2.1:通路URL——為啥通路 http://ip/admin就通路到了管理背景
# URL總入口
$ cat devops/urls.py
from django.contrib import admin
from django.urls import path
urlpatterns = [
# 通路admin的請求交給了admin.site.urls處理,而admin是django自帶的APP
path('admin/', admin.site.urls),
]
# devops項目總配置檔案
$ cat devops/settings.py
……
# Django自帶的APP都已經在這裡注冊好了,我們自己定義的app也得在這裡注冊
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'hello.apps.HelloConfig', # 添加此行
]
……
# 這些django自動的APP在哪呢?
$ ls ~/env3/lib/python3.6/site-packages/django/contrib/
admin admindocs auth contenttypes flatpages gis humanize __init__.py messages postgres __pycache__ redirects sessions sitemaps sites staticfiles syndication
# 找到admin這個APP的url
$ vim ~/env3/lib/python3.6/site-packages/django/contrib/admin/sites.py
……
def urls(self):
return self.get_urls(), 'admin', self.name
……
2.2:使用者發出的請求是數來處理的呢
URL已經将使用者請求帶到了admin的内部。使用者通路admin背景其實送出了兩個操作,第一是get請求admin頁面,admin給了一個清單框,要求填寫使用者名密碼;第二個是post請求是把使用者密碼送出給admin,那麼這兩個請求是誰來處理的呢——view
# admin app的view目錄下編寫應對使用者請求的各種邏輯,源碼可自行檢視
$ ls ~/env3/lib/python3.6/site-packages/django/contrib/admin/views/
autocomplete.py decorators.py __init__.py main.py
2.3:資料存在哪裡?資料表結構哪裡定義的呢?
vim ~/env3/lib/python3.6/site-packages/django/contrib/admin/models.py
2.4:使用者看的頁面各種樣式在哪裡定義的呢?
$ ls ~/env3/lib/python3.6/site-packages/django/contrib/admin/templates/admin/
404.html auth change_form_object_tools.html date_hierarchy.html filter.html login.html prepopulated_fields_js.html
500.html base.html change_list.html delete_confirmation.html includes object_history.html search_form.html
actions.html base_site.html change_list_object_tools.html delete_selected_confirmation.html index.html pagination.html submit_line.html
app_index.html change_form.html change_list_results.html edit_inline invalid_setup.html popup_response.html widgets
Django起步
1、建立工程
django-admin.py startproject devops
2、建立一個APP(應用)
Django架構的組織架構:一個項目(Project)下可以有多個應用(APP),每個應用下面都五髒俱全的MTV子產品(就是以py結尾的檔案),每個子產品各司其職。
qiangsh@Dream ~/D/P/5/Django_day1> cd devops/
qiangsh@Dream ~/D/P/5/D/devops> python manage.py startapp hello
qiangsh@Dream ~/D/P/5/D/devops> tree hello
hello
├── admin.py # 背景管理檔案
├── apps.py # app命名檔案
├── __init__.py # 初始化檔案,有他表示這是一個包
├── migrations # 資料遷移檔案
│ └── __init__.py
├── models.py # 模型檔案
├── tests.py
├── urls.py # 定義路由,預設沒有,自己加的
└── views.py # 邏輯處理,即控制器
2.1:全局配置檔案中注冊新建立的APP
$ cat devops/settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'hello.apps.HelloConfig', # 添加此行
]
注釋下面一行,解決權限問題
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
#'django.middleware.csrf.CsrfViewMiddleware', #注釋此行,解決跨域
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
2.2:編寫處理邏輯代碼(控制器)
$ cat hello/views.py
# Create your views here.
from django.shortcuts import render
from django.http import HttpResponse,QueryDict
# 練習一
# def index(request):
# return HttpResponse("<p>Hello World,Hello, Django</p>")
# 練習二
# 位置參數的接收方法---函數中的參數和URL中的位置一一對應(嚴重依賴參數順序且代碼可讀性不好,不推薦)
def index(request,year=2018,month=8):
# 普通參數的接受方法
# 方法一、設定預設值的方式擷取資料更優雅
year = request.GET.get("year","2019")
# 方法二、直接擷取資料,沒有傳值會報錯,不建議使用
month = request.GET["month"]
return HttpResponse("year is %s,month is %s" %(year,month))
# 關鍵字傳參數(?<參數名>參數類型)——視圖中直接通過參數名擷取值(最常用)
def index2(request,**kwargs):
# 請求參數接收,預設為GET請求,通過method判斷POST請求
if request.method == "POST":
print(request.scheme) # http
#print(request.method) #POST
print(request.body) #b'year=2019&month=11'
#print(type(request.body))
print(QueryDict(request.body).dict()) #{'year': '2018', 'month': '08'}
#print(type(QueryDict(request.body).dict()))
print(request.POST) #<QueryDict: {'year': ['2018'], 'month': ['08']}>
print(type(request.POST)) #<class 'django.http.request.QueryDict'>
data = request.POST
year = data.get('year',2018)
month = data.get('month',8)
else:
print(request)
print(request.method)
print(request.META)
print(request.body)
print(kwargs)
year = kwargs.get('year',2018)
month = kwargs.get('month',8)
return HttpResponse("year is %s,month is %s" %(year,month))
def user(request,**kwargs):
if request.method == "POST":
pass
else:
user = {'name':'qsh','age':'18'}
return render(request,'index.html',{'user':user})
2.3:編寫提供給使用者通路的路由URL
URL的設計比較優雅的方式:APP自己定義自己的url,然後在全局統一入口的url檔案中引入即可
#設計自己的url, 使用者通路/hello就會把請求發給views子產品中的index方法
$ cat hello/urls.py # 系統沒有,需要自己建立
from django.urls import path,re_path
from . import views
urlpatterns = [
# 2.3.1:普通傳參url基本和無參數一樣
# 請求方式 http://127.0.0.1:8000/hello/hello/?year=2019&month=10
path('index/', views.index, name='index'),
path('hello/',views.index2, name='index'),
# URL中每個位置數值和view中定義的參數順序一一對應(代碼可讀性不好,不推薦)
# 2.3.2:位置比對
# 請求方式 http://127.0.0.1:8000/hello/hello/2019/08/
re_path('hello/([0-9]{4})/([0-9]{2})/', views.index2, name='index2'),
# 2.3.3:關鍵字比對(最優雅) (?<參數名>參數類型)??視圖中直接通過參數名擷取值(最常用)
re_path('user/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/', views.user, name='user'),
]
#在統一通路url入口将hello的url引入進來(注冊子app的url)
$ cat devops/urls.py
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
path('hello/',include('hello.urls'),name="hello"),
]
# 總入口檔案又多了一層路徑,是以最終的通路路徑為 http://ip:8000/hello/<app_url>/
#最終路徑如下
$ tree
.
├── devops # devops工程自動的全局app
│ ├── __init__.py
│ ├── settings.py
│ ├── urls.py # 全局路由入口
│ └── wsgi.py
├── hello # 自己建立的app
│ ├── admin.py
│ ├── apps.py
│ ├── __init__.py
│ ├── migrations
│ │ └── __init__.py
│ ├── models.py
│ ├── tests.py
│ ├── urls.py # 每個app自定義的路由入口,需要注冊
│ └── views.py
└── manage.py
3 directories, 13 files
3、啟動工程
python manage.py runserver 0.0.0.0:8000
小結
以上這個小栗子其實隻用到了MTV中的View以及URL(url是view的指引,這兩個會一起出現,統稱為V),資料庫和模闆都沒用上,故而體驗不好,功能也簡單,好歹是跑通了。接下來一個完整的項目。在此之前把V和URL的最佳實戰知識學習下
MTV之視圖(URL&&View)
hello的小栗子主要實作了使用者發起請求,然後Django根據使用者發起的url路徑找到對應的處理函數,然後将内容簡單傳回而已。但現實中使用者的請求可不是這麼簡單。使用者都會有那些請求呢,大緻可以分為兩類讀和寫,讀有帶參數和不帶參數兩種場景,寫肯定是帶參數了
Django的MTV模式本質上和MVC是一樣的,也是為了各元件間保持松耦合關系,隻是定義上有些許不同
Django的MTV分别是值:
- M 代表模型(Model):負責業務對象和資料庫的關系映射(ORM)。
- T 代表模闆 (Template):負責如何把頁面展示給使用者(html)。
-
V 代表視圖(View):負責業務邏輯,并在适當時候調用Model和Template。
除了以上三層之外,還需要一個URL分發器,它的作用是将一個個URL的頁面請求分發給不同的View處理,View再調用相應的Model和
Template,MTV的響應模式如下所示:
- Web伺服器(中間件)收到一個http請求
- Django在URLconf裡查找對應的視圖(View)函數來處理http請求
- 視圖函數調用相應的資料模型來存取資料、調用相應的模闆向使用者展示頁面
- 視圖函數處理結束後傳回一個http的響應給Web伺服器
- Web伺服器将響應發送給用戶端
Django入門課程一準備環境web架構的設計邏輯Django起步MTV之視圖(URL&&View)表格練習表單練習頁面美化
4、添加html檔案
#添加模闆目錄 'DIRS': []
$ cat devops/settings.py
TEMPLATES = [
{
# 模闆引擎,翻譯給前端展示
'BACKEND': 'django.template.backends.django.DjangoTemplates',
# 模闆目錄,目前目錄下建立templates
'DIRS': [BASE_DIR+"/templates"],
# 如果統一目錄沒有,就在app自己目錄查找
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
#配置解釋
* BACKEND 是一個指向實作了Django模闆後端API的模闆引擎類的帶點的Python路徑。内置的後有django.template.backends.django.DjangoTemplates 和 django.template.backends.jinja2.Jinja2.兩個模闆差不多
* DIRS 定義了一個目錄清單,模闆引擎按清單順序搜尋這些目錄以查找模闆源檔案。預設會先找templates目錄
* APP_DIRS 告訴模闆引擎是否應該進入每個已安裝的應用中查找模闆。每種模闆引擎後端都定義了一個慣用的名稱作為應用内部存放模闆的子目錄名
qiangsh@Dream ~> cd devops
qiangsh@Dream ~/devops> mkdir templates/
qiangsh@Dream ~/devops> cat index.html
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
<title>python訓練營</title>
<head>
<body style="background:blue">
myname is {{ user.name }}, age is {{ user.age }}
</body>
</html>
5、浏覽器通路
5.1:帶參數的讀——get
- 使用者請求帶參數的url
# 普通參數 http://127.0.0.1:8000/hello/index/?year=2019&month=10
Django入門課程一準備環境web架構的設計邏輯Django起步MTV之視圖(URL&&View)表格練習表單練習頁面美化 # 位置參數 http://127.0.0.1:8000/hello/hello/2018/01/
Django入門課程一準備環境web架構的設計邏輯Django起步MTV之視圖(URL&&View)表格練習表單練習頁面美化
5.2:帶參數的寫——post
#shell終端,模拟django表單POST送出資料
curl -X POST http://127.0.0.1:8000/hello/hello/ -d 'year=2019&month=11'
http://127.0.0.1:8000/hello/user/2019/08/
6、QueryDict
通過上面示範我們知道無論GET/POST請求,接受參數的資料類型都是QueryDict。QueryDict到底做了什麼事情呢
在HttpRequest 對象中,GET 和POST 屬性是django.http.QueryDict 的執行個體,它是一個自定義的類似字典的類,用來處理同一個鍵帶有多個值。無論使用GET,POST方式,他們最終都是通過QueryDict方法對傳入的參數進行處理
# QueryDict常用方法
>>> QueryDict('a=1&a=2&c=3') # 對使用者請求的資料處理
<QueryDict: {'a': ['1', '2'], 'c': ['3']}>
>>> QueryDict.get(key, default=None) # 擷取資料
>>> q = QueryDict('a=1&a=2&a=3')
>>> q.lists()
[('a', ['1', '2', '3'])]
>>> q = QueryDict('a=1&b=3&c=5')
>>> q.dict()
{'a': '1','b':'3','c':'5'}
表格練習
1、修改邏輯代碼
$ cat hello/views.py
def user(request,**kwargs):
if request.method == "POST":
pass
else:
user = {'name':'qsh','age':'18'}
title = "devops"
books = ['python','java','php','web']
people = {'name':'qsh','age':18,'sex':'male'}
products = [{'pid': 1, 'name': 'iphone'}, {'pid': 2, 'name': 'computer'}, {'pid': 3, 'name': 'TV'}]
return render(request,'index.html',{'title':title,'books':books,'people':people,'user':user,'products':products})
2、修改html頁面
$ cat templates/index.html
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
<title>{{title}}</title>
<head>
<body style="background:blue">
{# 接受清單的第N個值,很low不推薦 #}
<li>{{books.0}}</li>
<li>{{books.1}}</li>
<li>{{books.2}}</li>
<li>{{books.3}}</li>
{# for循環标簽 ,渲染books清單 #}
{% for book in books %}
<li>{{book}}</li>
{% endfor %}
{# 接受字典中的定義的值 #}
<div style="color:orangered">hello my name is {{people.name}} </br>
my age is {{ people.age }} and I am {{ people.sex }}
</div>
{# if标簽使用,判斷user是否存在 #}
{% if people %}
<li>name:{{people.name}}</li>
{% else %}
使用者不存在
{% endif %}
{# for循環輸出字典裡所有的key,value #}
{% for k,v in people.items %}
<li>{{k}}-->{{v}}</li>
{% endfor %}
{# 清單頁展示 #}
{% for product in products %}
<li>ID:{{product.pid}},Name:{{product.name}}</li>
{% endfor %}
{# 清單頁展示,表格輸出 #}
<table border="1">
<thead> {# 定義表格的表頭 #}
<tr> {# 行 #}
<th>ID</th> {# 表頭單元格 - 包含表頭資訊 #}
<th>商品名</th>
</tr>
</thead>
<tbody>
{% for product in products %}
<tr>
<td> {{product.pid}} </td> {# 标準單元 - 包含資料 #}
<td> {{product.name}} </td>
</tr>
{% endfor %}
</tbody>
</table>
</body>
</html>
3、浏覽器通路
表單練習
$ cat hello/views.py
#添加子產品
from django.http import HttpResponse, QueryDict, HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
#建立登入函數
def login(request, **kwargs):
data = ""
if request.method == "POST":
print(request.POST)
print(QueryDict(request.body).dict())
username = request.POST.get('username','qsh')
passwd = request.POST.get('password','123456')
if username == "admin" and passwd == "123456":
# data = "welcome you %s" % username
return HttpResponseRedirect(reverse("hello:user"))
# return HttpResponseRedirect("/hello/hello/")
else:
data = "your passwd or username is wrong,plaeace again"
return render(request, 'login.html', {'data':data})
2、建立登入html
$ cat templates/login.html
<html>
<body>
<!--登陸表單-->
<form action="{% url 'hello:login' %}" method="post">
<!--使用者名-->
<input name="username" type="text" placeholder="使用者名"> </br>
<!--密碼-->
<input name="password" type="password" placeholder="密碼"> </br>
<button type="submit">登入</button>
</form>
{% if data %}
{{ data }}
{% endif %}
</body>
</html>
3、路由
$ cat hello/urls.py
from django.urls import path,re_path
from . import views
app_name = 'hello'
urlpatterns = [
path('index/', views.index, name='index'),
path('hello/',views.index2, name='hello'),
path('login/',views.login, name='login'),
path('index2/',views.user, name='user'),
re_path('hello/([0-9]{4})/([0-9]{2})/', views.index2, name='index2'),
re_path('user/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/', views.user, name='user'),
]
4、浏覽器通路
http://127.0.0.1:8000/hello/login/
使用者名密碼錯誤,效果如下。