python web架構學習筆記

來源:互聯網
上載者:User
一、web架構本質

1.基於socket,自己處理請求

#!/usr/bin/env python3#coding:utf8import socketdef handle_request(client): #接收請求 buf = client.recv(1024) print(buf) #返回資訊 client.send(bytes('

welcome liuyao webserver

','utf8'))def main(): #建立sock對象 sock = socket.socket() #監聽80連接埠 sock.bind(('localhost',8000)) #最大串連數 sock.listen(5) print('welcome nginx') #迴圈 while True: #等待使用者的串連,預設accept阻塞當有請求的時候往下執行 connection,address = sock.accept() #把串連交給handle_request函數 handle_request(connection) #關閉串連 connection.close()if __name__ == '__main__': main()

2.基於wsgi

WSGI,全稱 Web Server Gateway Interface,或者 Python Web Server Gateway Interface ,是為 Python 語言定義的 Web 服務器和 Web 應用程式或架構之間的一種簡單而通用的介面。自從 WSGI 被開發出來以後,許多其它語言中也出現了類似介面。

WSGI 的官方定義是,the Python Web Server Gateway Interface。從名字就可以看出來,這東西是一個Gateway,也就是網關。網關的作用就是在協議之間進行轉換。

WSGI 是作為 Web 服務器與 Web 應用程式或應用程式框架之間的一種低層級的介面,以提升可移植 Web 應用程式開發的共同點。WSGI 是基於現存的 CGI 標準而設計的。

很多架構都內建了 WSGI server ,比如 Flask,webpy,Django、CherryPy等等。當然效能都不好,內建的 web server 更多的是測試用途,發布時則使用生產環境的 WSGI server或者是聯合 nginx 做 uwsgi 。

python標準庫提供的獨立WSGI伺服器稱為wsgiref。

#!/usr/bin/env python#coding:utf-8#匯入wsgi模組from wsgiref.simple_server import make_serverdef 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() #接收請求 #預先處理請求(封裝了很多http請求的東西)

請求過來後就執行RunServer這個函數。

原理圖:

當使用者發送請求,socket將請求交給函數處理,之後再返回給使用者。

二、自訂web架構

python標準庫提供的wsgiref模組開發一個自己的Web架構

之前的使用wsgiref只能訪問一個url
下面這個可以根據你訪問的不同url請求進行處理並且返回給使用者

#!/usr/bin/env python#coding:utf-8from wsgiref.simple_server import make_serverdef RunServer(environ, start_response): start_response('200 OK', [('Content-Type','text/html')]) #根據url的不同,返回不同的字串 #1 擷取URL[URL從哪裡擷取?當請求過來之後執行RunServer, #wsgi給咱們封裝了這些請求,這些請求都封裝到了,environ & start_response] request_url = environ['PATH_INFO'] print (request_url) #2 根據URL做不同的相應 #print environ #這裡可以通過斷點來查看它都封裝了什麼資料 if request_url == '/login':  return [bytes("welcome login",'utf8')] elif request_url == '/reg':  return [bytes("welcome reg",'utf8')] else:  return [bytes('

404! no found

','utf8')]if __name__ == '__main__': httpd = make_server('', 8000, RunServer) print ("Serving HTTP on port 8000...") httpd.serve_forever()

當然 以上雖然根據不同url來進行處理,但是如果大量url的話,那麼代碼寫起來就很繁瑣。
所以使用下面方法進行處理

#!/usr/bin/env python#coding:utf-8from wsgiref.simple_server import make_serverdef index(): return [bytes('

index

','utf8')]def login(): return [bytes('

login

','utf8')]def reg(): return [bytes('

reg

','utf8')]def layout(): return [bytes('

layout

','utf8')]#定義一個列表 把url和上面的函數做一個對應urllist = [ ('/index',index), ('/login',login), ('/reg',reg), ('/layout',layout),]def RunServer(environ, start_response): start_response('200 OK', [('Content-Type','text/html')]) #根據url的不同,返回不同的字串 #1 擷取URL[URL從哪裡擷取?當請求過來之後執行RunServer,wsgi給咱們封裝了這些請求,這些請求都封裝到了,environ & start_response] request_url = environ['PATH_INFO'] print (request_url) #2 根據URL做不同的相應 #print environ #這裡可以通過斷點來查看它都封裝了什麼資料 #迴圈這個列表 找到你開啟的url 返回url對應的函數 for url in urllist: if request_url == url[0]: return url[1]() else: #url_list列表裡都沒有返回404 return [bytes('

404 not found

','utf8')] if __name__ == '__main__': httpd = make_server('', 8000, RunServer) print ("Serving HTTP on port 8000...") httpd.serve_forever()

三、模板引擎
對應上面的操作 都是根據使用者訪問的url返回給使用者一個字串的 比如return xxx

案例:

首先寫一個index.html頁面

內容:

index

welcome index

login.html頁面

內容:

  login 

welcome login

python代碼:

#!/usr/bin/env python #coding:utf-8from wsgiref.simple_server import make_serverdef 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')]) #根據url的不同,返回不同的字串 #1 擷取URL[URL從哪裡擷取?當請求過來之後執行RunServer,wsgi給咱們封裝了這些請求,這些請求都封裝到了,environ & start_response] request_url = environ['PATH_INFO'] print (request_url) #2 根據URL做不同的相應 #print environ #這裡可以通過斷點來查看它都封裝了什麼資料 for url in urllist:  #如果使用者請求的url和咱們定義的rul匹配  if request_url == url[0]:   #執行   return url[1]() else:  #url_list列表裡都沒有返回404  return [bytes('

404 not found

','utf8')]if __name__ == '__main__': httpd = make_server('', 8000, RunServer) print ("Serving HTTP on port 8000...") httpd.serve_forever()

但是以上內容只能返回給靜態內容,不能返回動態內容
那麼如何返回動態內容呢

自訂一套特殊的文法,進行替換

使用開源工具jinja2,遵循其指定文法

index.html 遵循jinja文法進行替換、迴圈、判斷

先展示大概效果,具體jinja2會在下章django筆記來進行詳細說明

index.html頁面

內容:

  Title  

{{ name }}

{{ age }}

{{ time }}

    {% for item in user_list %}
  • {{ item }}
  • {% endfor %}
{% if num == 1 %}

num == 1

{% else %}

num == 2

{% endif %}

python代碼:

#!/usr/bin/env python#-*- coding:utf-8 -*-import time #匯入wsgi模組from wsgiref.simple_server import make_server#匯入jinja模組from jinja2 import Templatedef 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迴圈 操作 #這裡需要注意因為預設是的unicode的編碼所以設定為utf-8 return [bytes(result,'utf8')]urllist = [ ('/index',index),]def RunServer(environ, start_response): start_response('200 OK', [('Content-Type', 'text/html')]) #根據url的不同,返回不同的字串 #1 擷取URL[URL從哪裡擷取?當請求過來之後執行RunServer, # wsgi給咱們封裝了這些請求,這些請求都封裝到了,environ & start_response] request_url = environ['PATH_INFO'] print(request_url) #2 根據URL做不同的相應 #迴圈這個列表 for url in urllist:  #如果使用者請求的url和咱們定義的rul匹配  if request_url == url[0]:   print (url)   return url[1]() else:  #urllist列表裡都沒有返回404  return [bytes('

404 not found

','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)的縮寫,一種軟體設計典範,用一種商務邏輯、資料、介面顯示分離的方法組織代碼,將商務邏輯聚集到一個組件裡面,在改進和個人化定製介面及使用者互動的同時,不需要重新編寫商務邏輯。MVC被獨特的發展起來用於映射傳統的輸入、處理和輸出功能在一個邏輯的圖形化使用者介面的結構中。

將路由規則放入urls.py

操作urls的放入controller裡的func函數

將資料庫操作黨風model裡的db.py裡

將html頁面等放入views裡

原理圖:

2.MTV

Models 處理DB操作

Templates html模板

Views 處理函數請求

原理圖:

以上就是本文的全部內容,希望對大家的學習有所協助。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.