Django的学习需要掌握的一些基础和初步搭建自己的框架
一.Django的學(xué)習(xí)需要掌握的一些基礎(chǔ)
第一個需要注意的點:客戶端發(fā)送過來的數(shù)據(jù)結(jié)構(gòu)組成:
第二個需要注意的點:動態(tài)網(wǎng)頁和靜態(tài)網(wǎng)頁
靜態(tài)網(wǎng)頁:用戶發(fā)送請求,服務(wù)端找到對應(yīng)的靜態(tài)文件返回給瀏覽器,靜態(tài)網(wǎng)頁時不變的,用戶恮什么就返回什么,不能和用戶交互。
動態(tài)網(wǎng)頁:動態(tài)網(wǎng)頁和靜態(tài)網(wǎng)頁的區(qū)別就是動態(tài)網(wǎng)頁能和用戶進行交互,根據(jù)用戶的需求隨時調(diào)換不同的靜態(tài)頁面返回給瀏覽器。
疑問:1.wsgiref怎么把套接字封裝的?
?
WSGI_APPLICATION = 'untitled7.wsgi.application'wsgiref是把socket封裝起來,不用再去手動生成。
?
2.make_server()和serve_forever()
? ?3.ico圖標的問題
?
?請求頭最后的\r\n是標識著請求頭的結(jié)束,請求體即將開始。我的理解是兩個\r\n是他們中間空一格,兩次換行,開啟請求體內(nèi)容輸出,更好的區(qū)分頭和體。
1 import socket 2 # 客戶端和服務(wù)端的傳輸:套接字通信 3 soc=socket.socket() 4 # 綁定的是元組 5 soc.bind(('127.0.0.1',8001)) 6 soc.listen(5) 7 8 # 通信循環(huán) 9 while True: 10 print('監(jiān)聽8001端口') 11 # addr是客戶端的IP+Port 12 #conn是建雙向連接對象,soc是套接字對象 13 conn,addr=soc.accept() 14 # 接收到的客戶端數(shù)據(jù) 15 data=conn.recv(1024) 16 # 轉(zhuǎn)換成str類型 17 # str()函數(shù)里面第一個參數(shù)是需要轉(zhuǎn)的數(shù)據(jù),第二個是指定的字符編碼類型。下面是將二進制轉(zhuǎn)成字符串 18 data=str(data,encoding='utf-8') 19 print(data) 20 # 我們打印獲得的字符串,發(fā)現(xiàn)客戶端發(fā)送過來的數(shù)據(jù)之間是按照'\r\n'有規(guī)律的分開的,待會再說分開有何意義。 21 # 我們可以將這些數(shù)據(jù)按照發(fā)現(xiàn)的規(guī)律用split分割開來,返回一個有一定規(guī)律的列表。 22 # 取出列表第一個,再把他們通過空格分開來,返回一個請求首行組成的列表。 23 resquest_list=data.split('\r\n') 24 first_list=resquest_list[0].split(' ') 25 conn.send(b'HTTP/1.1 200 OK\r\nContent-Type:text/html\r\n\r\n') 26 if first_list[1]=='/index': # 如果請求首行第二個元素(也就是請求地址)等于'/index' 27 # conn.send('<h1>index</h1><img src="https://gss0.bdstatic.com/-4o3dSag_xI4khGkpoWK1HF6hhy/baike/c0%3Dbaike92%2C5%2C5%2C92%2C30/sign=775f519ac08065386fe7ac41f6b4ca21/fd039245d688d43f63d84526771ed21b0ff43bf5.jpg">'.encode('utf-8')) 28 with open('index.html','rb')as f: 29 data=f.read() 30 conn.send(data) # 將服務(wù)端的數(shù)據(jù)發(fā)送給瀏覽器,瀏覽器對數(shù)據(jù)進行渲染=====》靜態(tài)網(wǎng)頁 數(shù)據(jù)寫死了 31 elif first_list[1]=='/two': 32 with open('two.html','r',encoding='utf-8')as f: 33 data=f.read() 34 import datetime 35 now=datetime.datetime.now().strftime('%Y-%m-%d %X') 36 data=data.replace('@@time@@',now) # ======》動態(tài)網(wǎng)頁 網(wǎng)頁數(shù)據(jù)沒有固定死 37 conn.send(data.encode('utf-8')) 38 else: 39 conn.send(b'404') 40 41 42 # print(data) 43 # 44 # conn.send(b'HTTP/1.1 200 OK \r\n\r\nhello web') 45 conn.close() 46 47 ''' 48 # 請求首行:請求類型 請求地址 請求協(xié)議 49 GET /index HTTP/1.1\r\n 50 # 請求頭 51 Host: 127.0.0.1:8001\r\n 52 Connection: keep-alive\r\n 53 Cache-Control: max-age=0\r\n 54 Upgrade-Insecure-Requests: 1\r\n 55 User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36\r\n 56 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\r\n 57 Accept-Encoding: gzip, deflate, br\r\n 58 Accept-Language: zh-CN,zh;q=0.9\r\n\r\n' 59 60 # 請求體 61 。。。。 62 63 ''' 基礎(chǔ)知識點-一個簡單的請求與回響?
?
?
請求---》處理---》調(diào)用函數(shù)---》打開模板和數(shù)據(jù)庫---》返回數(shù)據(jù)給瀏覽器---》瀏覽器解析渲染
下面分三個文件來說明:
用wsgiref搭建簡單的服務(wù)端
1 from wsgiref.simple_server import make_server 2 import my_urls 3 from views import * 4 5 6 def my_server(environ, start_response): 7 # print(environ) environ返回的是一個字典,path_info是字典里的key,對應(yīng)的值是請求地址 8 print(environ['PATH_INFO']) # 'PATH_INFO': '/index' PATH_INFO就是請求地址 9 start_response('200 OK', [('Content-Type', 'text/html')]) # 服務(wù)器響應(yīng)狀態(tài)碼:200 文本類型:text 10 func=None 11 for url in my_urls.urls: 12 if url[0]==environ['PATH_INFO']: 13 func=url[1] # 這里的func是函數(shù)地址 14 break # 結(jié)束循環(huán) 15 if func: 16 # 固定寫法,如果不寫environ也可以,但是要求函數(shù)必須也不能有形參 17 # 不寫的話報錯:missing 1 required positional argument: 'response' 18 response=func(environ) 19 else: 20 response= error(environ) 21 22 return [response,] # 這里是固定返回一個列表,用別人的就要按照別人的要求來 23 24 25 if __name__ == '__main__': 26 27 my=make_server('127.0.0.1',8002,my_server) 28 my.serve_forever() 搭建簡單服務(wù)器?
視圖函數(shù)
用到j(luò)inja2模塊中的template
1 # 視圖函數(shù) 2 import pymysql 3 from jinja2 import Template 4 def index(response): 5 with open('templates/index.html','r',encoding='utf-8') as f: 6 data=f.read() 7 8 return data.encode('utf-8') 9 10 def time(response): 11 import datetime 12 now=datetime.datetime.now().strftime('%Y-%m-%d %X') 13 with open('templates/two.html','r',encoding='utf-8') as f: 14 data=f.read() 15 data=data.replace('@@time@@',now) 16 return data.encode('utf-8') 17 18 19 def user_list(response): 20 # 連接數(shù)據(jù)庫拿數(shù)據(jù) 21 # 拿到一個數(shù)據(jù)庫連接 22 conn=pymysql.connect(host='127.0.0.1',port=3306,user='root',database='test',password='egon123') 23 # 拿到一個游標對象 24 cursor=conn.cursor(cursor=pymysql.cursors.DictCursor) 25 # 執(zhí)行sql 26 cursor.execute('select * from user') 27 # 把數(shù)據(jù)拿出來 28 user_list=cursor.fetchall() 29 print(user_list) 30 with open('templates/user_list.html','r',encoding='utf-8')as f: 31 data=f.read() 32 # 生成一個模板對象,需要傳字符串 33 template=Template(data) 34 # 相當(dāng)于在執(zhí)行data.replace(),返回替換完成的字符串 35 data=template.render(user_list=user_list) 36 37 38 39 return data.encode('utf-8') 40 def error(request): 41 return '404'.encode('utf-8') 42 43 44 def favicon(request): 45 with open('favicon.ico','rb') as f: 46 data=f.read() 47 return data 視圖函數(shù)?
路由:路由的作用就是建立請求地址與索引之間的關(guān)系--》服務(wù)端解析出請求地址,然后調(diào)用對應(yīng)的函數(shù)
import views # 路由 urls=[('/index',views.index),('/time',views.time),('/user_list',views.user_list),('/favicon.ico',views.favicon), ] 路由?
下面是三個模板中的html文件
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 </head> 7 <body> 8 9 <img src="https://gss0.bdstatic.com/-4o3dSag_xI4khGkpoWK1HF6hhy/baike/c0%3Dbaike92%2C5%2C5%2C92%2C30/sign=775f519ac08065386fe7ac41f6b4ca21/fd039245d688d43f63d84526771ed21b0ff43bf5.jpg">' 10 11 </body> 12 </html> index.html 1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 </head> 7 <body> 8 @@time@@ 9 </body> 10 </html> two.html <!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>用戶列表</title> </head> <body><table border="1"><thead><tr><th>id</th><th>用戶名</th><th>密碼</th></tr></thead><tbody>{% for user in user_list%}<tr><td>{{user.id}}</td><td>{{user.name}}</td><td>{{user.password}}</td></tr>{%endfor%}</tbody></table></body> </html> user_list.html?
放一張簡單的django工作圖
附上文字說明:
圖片解析:瀏覽器向服務(wù)器發(fā)送url地址:ip+port+請求地址 ,服務(wù)端對請求地址進行解析,獲得客戶端發(fā)來的請求地址,然后通過路由循環(huán)服務(wù)端的請求地址,有匹配成功的就調(diào)用服務(wù)端的函數(shù),函數(shù)從模板templates中調(diào)用html文件,如果需要從數(shù)據(jù)庫
調(diào)用數(shù)據(jù)則需要導(dǎo)入pymysql,獲得的數(shù)據(jù)列表最后需要通過模板對象進行渲染,瀏覽器客戶端解析html,并對模板按照要求進行
相應(yīng)的渲染。
很形象的一個流程圖
二.初步搭建自己的框架
1.安裝django的三種方式
方式二
方式三
?
2.如何創(chuàng)建自己的django項目?
1.首先切換到一個放項目的目錄下
2.在命令行輸入:
django-admin startproject django項目名3.切換到項目目錄,啟動manage文件 python3 manage.py runserver
可以通過端口+ip查看自己的django項目
3.如何在pycharm里啟動Django?
3.1 直接在新窗口打開django所在位置
terminal運行python3 manage.py runserver
?
?
?
轉(zhuǎn)載于:https://www.cnblogs.com/Roc-Atlantis/p/9543978.html
總結(jié)
以上是生活随笔為你收集整理的Django的学习需要掌握的一些基础和初步搭建自己的框架的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 随笔7
- 下一篇: str字符串 encoding( ) 方