1. 程式人生 > >python----web框架

python----web框架

data 交互 span spa 代碼 pytho lap 字符串 encoding

Web框架本質

1、眾所周知,對於所有的Web應用,本質上其實就是一個socket服務端,用戶的瀏覽器其實就是一個socket客戶端

#!/usr/bin/env python
# -*- coding:utf-8 -*-
#-Author-Lian
 
import socket
 
def handle_request(client):
    buf = client.recv(1024)
    client.send("HTTP/1.1 200 OK\r\n\r\n".encode("utf-8"))
    client.send("Hello, Seven".encode("utf-8"))
 
def main():
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.bind((‘localhost‘, 8000))
    sock.listen(5)
    while True:
        connection, address = sock.accept()
        handle_request(connection)
        connection.close()
 
if __name__ == ‘__main__‘:
    main()

執行上面程序,直接用瀏覽器訪問http://127.0.0.1:8000/就能顯示發送的信息

上述通過socket來實現了其本質,而對於真實開發中的python web程序來說,一般會分為兩部分:服務器程序和應用程序。服務器程序負責對socket服務器進行封裝,並在請求到來時,對請求的各種數據進行整理。應用程序則負責具體的邏輯處理。為了方便應用程序的開發,就出現了眾多的Web框架,例如:Django、Flask、web.py 等。不同的框架有不同的開發方式,但是無論如何,開發出的應用程序都要和服務器程序配合,才能為用戶提供服務。這樣,服務器程序就需要為不同的框架提供不同的支持。這樣混亂的局面無論對於服務器還是框架,都是不好的。對服務器來說,需要支持各種不同框架,對框架來說,只有支持它的服務器才能被開發出的應用使用。這時候,標準化就變得尤為重要。我們可以設立一個標準,只要服務器程序支持這個標準,框架也支持這個標準,那麽他們就可以配合使用。一旦標準確定,雙方各自實現。這樣,服務器可以支持更多支持標準的框架,框架也可以使用更多支持標準的服務器;WSGI(Web Server Gateway Interface)是一種規範,它定義了使用python編寫的web app與web server之間接口格式,實現web app與web server間的解耦

2、python標準庫提供的獨立WSGI服務器稱為wsgiref

#!/usr/bin/env python
# -*- coding:utf-8 -*-
#-Author-Lian
 
from wsgiref.simple_server import make_server
 
def RunServer(environ, start_response):
    start_response(‘200 OK‘, [(‘Content-Type‘, ‘text/html‘)])
    return [‘<h1>Hello, web!</h1>‘.encode("utf-8"),]
 
if __name__ == ‘__main__‘:
    httpd = make_server(‘‘, 8000, RunServer)
    print("Serving HTTP on port 8000...")
    httpd.serve_forever()

更少的代碼實現web交互

轉換字符串為字節形式:

1.b‘ffff‘
2.bytes(‘ffff‘,encoding=‘utf8‘)
3.‘ffff‘.encoding(‘utf-8‘)

自定義Web框架

通過python標準庫提供的wsgiref模塊開發一個自己的Web框架

from wsgiref.simple_server import make_server
 
def handel_index():
    return [‘<h1>Hello, index!</h1>‘.encode("utf-8"), ]
 
def handel_data():
    return [‘<h1>Hello, data!</h1>‘.encode("utf-8"), ]
 
URL_DICT={
    ‘/index‘:handel_index,
    ‘/data‘:handel_data,
}
 
def RunServer(environ, start_response):
    #start_response 封裝返回給用戶的數據
    start_response(‘200 OK‘, [(‘Content-Type‘, ‘text/html‘)])
    #environ 客戶發來的數據
    current_url = environ[‘PATH_INFO‘]
    func = None
    if current_url in URL_DICT:
        func = URL_DICT[current_url]
    if func:
        return func()
    else:
        return [‘<h1>Error 404</h1>‘.encode("utf-8"), ]
 
if __name__ == ‘__main__‘:
    httpd = make_server(‘‘, 8009, RunServer)
    print("Serving HTTP on port 8000...")
    httpd.serve_forever()

2、模板引擎

在上一步驟中,對於所有的login、index均返回給用戶瀏覽器一個簡單的字符串,在現實的Web請求中一般會返回一個復雜的符合HTML規則的字符串,所以我們一般將要返回給用戶的HTML寫在指定文件中,然後再返回。如:

技術分享
<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <form>
        <input type="text" />
        <input type="text" />
        <input type="submit" />
    </form>
</body>
</html>

data.html
data.html 技術分享
<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <h1>Index</h1>
</body>
</html>

index.html
index.html
from wsgiref.simple_server import make_server
 
def handel_index():
    f = open(‘index.html‘,‘rb‘)
    data = f.read()
    return [data,]
    # return [‘<h1>Hello, index!</h1>‘.encode("utf-8"), ]
 
def handel_data():
    f = open(‘data.html‘,‘rb‘)
    data = f.read()
    return [data,]
    # return [‘<h1>Hello, data!</h1>‘.encode("utf-8"), ]
 
URL_DICT={
    ‘/index‘:handel_index,
    ‘/data‘:handel_data,
}
 
def RunServer(environ, start_response):
    #start_response 封裝返回給用戶的數據
    start_response(‘200 OK‘, [(‘Content-Type‘, ‘text/html‘)])
    #environ 客戶發來的數據
    current_url = environ[‘PATH_INFO‘]
    func = None
    if current_url in URL_DICT:
        func = URL_DICT[current_url]
    if func:
        return func()
    else:
        return [‘<h1>Error 404</h1>‘.encode("utf-8"), ]
 
if __name__ == ‘__main__‘:
    httpd = make_server(‘‘, 8009, RunServer)
    print("Serving HTTP on port 8000...")
    httpd.serve_forever()

對於上述代碼,雖然可以返回給用戶HTML的內容以現實復雜的頁面,但是還是存在問題:如何給用戶返回動態內容?

3、返回動態頁面數據

  • 自定義一套特殊的語法,進行替換
  • 使用開源工具jinja2,遵循其指定語法
#!/usr/bin/env python
# -*- coding:utf-8 -*-
#-Author-Lian
 
from wsgiref.simple_server import make_server
 
def handel_index():
    f = open(‘index.html‘,‘rb‘)
    data = f.read()
    data = data.replace(b‘Index‘,"程榮華吃骨頭".encode("utf-8"))
    return [data,]
    # return [‘<h1>Hello, index!</h1>‘.encode("utf-8"), ]
 
def handel_data():
    f = open(‘data.html‘,‘rb‘)
    data = f.read()
    return [data,]
    # return [‘<h1>Hello, data!</h1>‘.encode("utf-8"), ]
 
URL_DICT={
    ‘/index‘:handel_index,
    ‘/data‘:handel_data,
}
 
def RunServer(environ, start_response):
    #start_response 封裝返回給用戶的數據
    start_response(‘200 OK‘, [(‘Content-Type‘, ‘text/html‘)])
    #environ 客戶發來的數據
    current_url = environ[‘PATH_INFO‘]
    func = None
    if current_url in URL_DICT:
        func = URL_DICT[current_url]
    if func:
        return func()
    else:
        return [‘<h1>Error 404</h1>‘.encode("utf-8"), ]
 
if __name__ == ‘__main__‘:
    httpd = make_server(‘‘, 8009, RunServer)
    print("Serving HTTP on port 8000...")
    httpd.serve_forever()

4、WEB框架

實際為文件夾的結構區分。

MVC
    Model View Controller
    數據庫 模板文件 業務處理
MTV
    Model Template View
    數據庫 模板文件 業務處理

上例修改為MVC框架後,如圖

技術分享

技術分享
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# __author__ = "life"
# Email: [email protected]
# Date: 2017/5/28

def handle_index():
    import time
    v = str(time.time())
    f  = open(view/index.html,mode=rb)
    data = f.read()
    f.close()
    data = data.replace(b@uuuuu,v.encode(utf-8))
    return [data,]

def handle_date():
    return [<h1>Hello,Date!</h1>.encode(utf-8), ]

dict={a}
account.py 技術分享
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# __author__ = "life"
# Email: [email protected]
# Date: 2017/5/28

from wsgiref.simple_server import make_server
from controller import account

URL_DICT={"/index":account.handle_index,"/date":account.handle_date}

def RunServer(environ, start_response):
    # environ 客戶發來的所有數據
    # start_response 封裝要返回給用戶的數據,響應頭狀態碼
    start_response(200 ok, [(Content-Type, text/html)])
    current_url = environ[PATH_INFO]
    func = None
    if current_url in URL_DICT:
        func = URL_DICT[current_url]
    if func:
        return func()
    else:
        return [<h1>404!</h1>.encode(utf-8), ]
    # 返回的內容
    # return [‘<h1>Hello,web!</h1>‘.encode(‘utf-8‘), ]


if __name__ == __main__:
    httpd = make_server(‘‘, 8000, RunServer)
    print(Server HTTP on port 8000...)
    httpd.serve_forever()
s3.py 技術分享
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>[email protected]</h1>
</body>
</html>
index.html

Django為MTV類型web框架

 

  

 

 

python----web框架