python web框架學(xué)習(xí)筆記
一、web框架本質(zhì)
1.基于socket,自己處理請求
#!/usr/bin/env python3
#coding:utf8
import socket
def handle_request(client):
#接收請求
buf = client.recv(1024)
print(buf)
#返回信息
client.send(bytes('<h1>welcome liuyao webserver</h1>','utf8'))
def main():
#創(chuàng)建sock對象
sock = socket.socket()
#監(jiān)聽80端口
sock.bind(('localhost',8000))
#最大連接數(shù)
sock.listen(5)
print('welcome nginx')
#循環(huán)
while True:
#等待用戶的連接,默認(rèn)accept阻塞當(dāng)有請求的時候往下執(zhí)行
connection,address = sock.accept()
#把連接交給handle_request函數(shù)
handle_request(connection)
#關(guān)閉連接
connection.close()
if __name__ == '__main__':
main()
2.基于wsgi
WSGI,全稱 Web Server Gateway Interface,或者 Python Web Server Gateway Interface ,是為 Python 語言定義的 Web 服務(wù)器和 Web 應(yīng)用程序或框架之間的一種簡單而通用的接口。自從 WSGI 被開發(fā)出來以后,許多其它語言中也出現(xiàn)了類似接口。
WSGI 的官方定義是,the Python Web Server Gateway Interface。從名字就可以看出來,這東西是一個Gateway,也就是網(wǎng)關(guān)。網(wǎng)關(guān)的作用就是在協(xié)議之間進行轉(zhuǎn)換。
WSGI 是作為 Web 服務(wù)器與 Web 應(yīng)用程序或應(yīng)用框架之間的一種低級別的接口,以提升可移植 Web 應(yīng)用開發(fā)的共同點。WSGI 是基于現(xiàn)存的 CGI 標(biāo)準(zhǔn)而設(shè)計的。
很多框架都自帶了 WSGI server ,比如 Flask,webpy,Django、CherryPy等等。當(dāng)然性能都不好,自帶的 web server 更多的是測試用途,發(fā)布時則使用生產(chǎn)環(huán)境的 WSGI server或者是聯(lián)合 nginx 做 uwsgi 。
python標(biāo)準(zhǔn)庫提供的獨立WSGI服務(wù)器稱為wsgiref。
#!/usr/bin/env python
#coding:utf-8
#導(dǎo)入wsgi模塊
from wsgiref.simple_server import make_server
def RunServer(environ, start_response):
start_response('200 OK', [('Content-Type', 'text/html')])
return [bytes("welcome webserver".encode('utf8'))]
if __name__ == '__main__':
httpd = make_server('', 8000, RunServer)
print ("Serving HTTP on port 8000...")
httpd.serve_forever()
#接收請求
#預(yù)處理請求(封裝了很多http請求的東西)
請求過來后就執(zhí)行RunServer這個函數(shù)。
原理圖:

當(dāng)用戶發(fā)送請求,socket將請求交給函數(shù)處理,之后再返回給用戶。
二、自定義web框架
python標(biāo)準(zhǔn)庫提供的wsgiref模塊開發(fā)一個自己的Web框架
之前的使用wsgiref只能訪問一個url
下面這個可以根據(jù)你訪問的不同url請求進行處理并且返回給用戶
#!/usr/bin/env python
#coding:utf-8
from wsgiref.simple_server import make_server
def RunServer(environ, start_response):
start_response('200 OK', [('Content-Type','text/html')])
#根據(jù)url的不同,返回不同的字符串
#1 獲取URL[URL從哪里獲取?當(dāng)請求過來之后執(zhí)行RunServer,
#wsgi給咱們封裝了這些請求,這些請求都封裝到了,environ & start_response]
request_url = environ['PATH_INFO']
print (request_url)
#2 根據(jù)URL做不同的相應(yīng)
#print environ #這里可以通過斷點來查看它都封裝了什么數(shù)據(jù)
if request_url == '/login':
return [bytes("welcome login",'utf8')]
elif request_url == '/reg':
return [bytes("welcome reg",'utf8')]
else:
return [bytes('<h1>404! no found</h1>','utf8')]
if __name__ == '__main__':
httpd = make_server('', 8000, RunServer)
print ("Serving HTTP on port 8000...")
httpd.serve_forever()
當(dāng)然 以上雖然根據(jù)不同url來進行處理,但是如果大量url的話,那么代碼寫起來就很繁瑣。
所以使用下面方法進行處理
#!/usr/bin/env python
#coding:utf-8
from wsgiref.simple_server import make_server
def index():
return [bytes('<h1>index</h1>','utf8')]
def login():
return [bytes('<h1>login</h1>','utf8')]
def reg():
return [bytes('<h1>reg</h1>','utf8')]
def layout():
return [bytes('<h1>layout</h1>','utf8')]
#定義一個列表 把url和上面的函數(shù)做一個對應(yīng)
urllist = [
('/index',index),
('/login',login),
('/reg',reg),
('/layout',layout),
]
def RunServer(environ, start_response):
start_response('200 OK', [('Content-Type','text/html')])
#根據(jù)url的不同,返回不同的字符串
#1 獲取URL[URL從哪里獲取?當(dāng)請求過來之后執(zhí)行RunServer,wsgi給咱們封裝了這些請求,這些請求都封裝到了,environ & start_response]
request_url = environ['PATH_INFO']
print (request_url)
#2 根據(jù)URL做不同的相應(yīng)
#print environ #這里可以通過斷點來查看它都封裝了什么數(shù)據(jù)
#循環(huán)這個列表 找到你打開的url 返回url對應(yīng)的函數(shù)
for url in urllist:
if request_url == url[0]:
return url[1]()
else:
#url_list列表里都沒有返回404
return [bytes('<h1>404 not found</h1>','utf8')]
if __name__ == '__main__':
httpd = make_server('', 8000, RunServer)
print ("Serving HTTP on port 8000...")
httpd.serve_forever()
三、模板引擎
對應(yīng)上面的操作 都是根據(jù)用戶訪問的url返回給用戶一個字符串的 比如return xxx
案例:
首先寫一個index.html頁面
內(nèi)容:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>index</title> </head> <body> <h1>welcome index</h1> </body> </html>
login.html頁面
內(nèi)容:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>login</title> </head> <body> <h1>welcome login</h1> <form> user:<input type="text"/> pass:<input type="password"/> <button type="button">login in</button> </form> </body> </html>
python代碼:
#!/usr/bin/env python
#coding:utf-8
from wsgiref.simple_server import make_server
def index():
#把index頁面讀進來返回給用戶
indexfile = open('index.html','r+').read()
return [bytes(indexfile,'utf8')]
def login():
loginfile = open('login.html','r+').read()
return [bytes(loginfile,'utf8')]
urllist = [
('/login',login),
('/index',index),
]
def RunServer(environ, start_response):
start_response('200 OK', [('Content-Type','text/html')])
#根據(jù)url的不同,返回不同的字符串
#1 獲取URL[URL從哪里獲取?當(dāng)請求過來之后執(zhí)行RunServer,wsgi給咱們封裝了這些請求,這些請求都封裝到了,environ & start_response]
request_url = environ['PATH_INFO']
print (request_url)
#2 根據(jù)URL做不同的相應(yīng)
#print environ #這里可以通過斷點來查看它都封裝了什么數(shù)據(jù)
for url in urllist:
#如果用戶請求的url和咱們定義的rul匹配
if request_url == url[0]:
#執(zhí)行
return url[1]()
else:
#url_list列表里都沒有返回404
return [bytes('<h1>404 not found</h1>','utf8')]
if __name__ == '__main__':
httpd = make_server('', 8000, RunServer)
print ("Serving HTTP on port 8000...")
httpd.serve_forever()
但是以上內(nèi)容只能返回給靜態(tài)內(nèi)容,不能返回動態(tài)內(nèi)容
那么如何返回動態(tài)內(nèi)容呢
自定義一套特殊的語法,進行替換
使用開源工具jinja2,遵循其指定語法
index.html 遵循jinja語法進行替換、循環(huán)、判斷
先展示大概效果,具體jinja2會在下章django筆記來進行詳細(xì)說明
index.html頁面
內(nèi)容:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<!--general replace-->
<h1>{{ name }}</h1>
<h1>{{ age }}</h1>
<h1>{{ time }}</h1>
<!--for circular replace-->
<ul>
{% for item in user_list %}
<li>{{ item }}</li>
{% endfor %}
</ul>
<!--if else judge-->
{% if num == 1 %}
<h1>num == 1</h1>
{% else %}
<h1>num == 2</h1>
{% endif %}
</body>
</html>
python代碼:
#!/usr/bin/env python
#-*- coding:utf-8 -*-
import time
#導(dǎo)入wsgi模塊
from wsgiref.simple_server import make_server
#導(dǎo)入jinja模塊
from jinja2 import Template
def index():
#打開index.html
data = open('index.html').read()
#使用jinja2渲染
template = Template(data)
result = template.render(
name = 'yaoyao',
age = '18',
time = str(time.time()),
user_list = ['linux','python','bootstarp'],
num = 1
)
#同樣是替換為什么用jinja,因為他不僅僅是文本的他還支持if判斷 & for循環(huán) 操作
#這里需要注意因為默認(rèn)是的unicode的編碼所以設(shè)置為utf-8
return [bytes(result,'utf8')]
urllist = [
('/index',index),
]
def RunServer(environ, start_response):
start_response('200 OK', [('Content-Type', 'text/html')])
#根據(jù)url的不同,返回不同的字符串
#1 獲取URL[URL從哪里獲取?當(dāng)請求過來之后執(zhí)行RunServer,
# wsgi給咱們封裝了這些請求,這些請求都封裝到了,environ & start_response]
request_url = environ['PATH_INFO']
print(request_url)
#2 根據(jù)URL做不同的相應(yīng)
#循環(huán)這個列表
for url in urllist:
#如果用戶請求的url和咱們定義的rul匹配
if request_url == url[0]:
print (url)
return url[1]()
else:
#urllist列表里都沒有返回404
return [bytes('<h1>404 not found</h1>','utf8')]
if __name__ == '__main__':
httpd = make_server('', 8000, RunServer)
print ("Serving HTTP on port 8000...")
httpd.serve_forever()
四、MVC和MTV
1.MVC
全名是Model View Controller,是模型(model)-視圖(view)-控制器(controller)的縮寫,一種軟件設(shè)計典范,用一種業(yè)務(wù)邏輯、數(shù)據(jù)、界面顯示分離的方法組織代碼,將業(yè)務(wù)邏輯聚集到一個部件里面,在改進和個性化定制界面及用戶交互的同時,不需要重新編寫業(yè)務(wù)邏輯。MVC被獨特的發(fā)展起來用于映射傳統(tǒng)的輸入、處理和輸出功能在一個邏輯的圖形化用戶界面的結(jié)構(gòu)中。

將路由規(guī)則放入urls.py
操作urls的放入controller里的func函數(shù)
將數(shù)據(jù)庫操作黨風(fēng)model里的db.py里
將html頁面等放入views里
原理圖:

2.MTV
Models 處理DB操作
Templates html模板
Views 處理函數(shù)請求

原理圖:

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助。
相關(guān)文章
python之plt.hist函數(shù)的輸入?yún)?shù)和返回值的用法解釋
這篇文章主要介紹了python之plt.hist函數(shù)的輸入?yún)?shù)和返回值的用法解釋,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-10-10
Pyspark獲取并處理RDD數(shù)據(jù)代碼實例
這篇文章主要介紹了Pyspark獲取并處理RDD數(shù)據(jù)代碼實例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-03-03
解決Keyerror ''''acc'''' KeyError: ''''val_acc''''問題
這篇文章主要介紹了解決Keyerror 'acc' KeyError: 'val_acc'問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-06-06
Keras設(shè)置以及獲取權(quán)重的實現(xiàn)
這篇文章主要介紹了Keras設(shè)置以及獲取權(quán)重的實現(xiàn),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-06-06

