Web 框架本質解析

一  Web框架本質

1. 本身開發Web框架 - socket - http協議 - HTML知識 - 數據庫(pymysql,SQLAlchemy) HTTP: 無狀態、短鏈接 TCP: 不斷開 WEB應用(網站): Http協議: 發送: POST /index HTTP/1.1 Host: 127.0.0.1:8080 Connection: keep-alive Cache-Control: max-age=0 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.89 Safari/537.36 HTTPS: 1 Accept-Encoding: gzip, deflate, sdch Accept-Language: zh-CN,zh;q=0.8 Cookie: csrftoken=hNmu2JOtntGMN0hSRSPmMQk2newEb3o8zb6pXW5Cc3m54IaA5VlTkUvqWsFezpni p=123 響應: 200 OK Cache-Control:public, max-age=15 Connection:keep-alive Content-Encoding:gzip Content-Type:text/html; charset=utf-8 Date:Wed, 14 Jun 2017 01:21:17 GMT Expires:Wed, 14 Jun 2017 01:21:33 GMT Last-Modified:Wed, 14 Jun 2017 01:21:03 GMT Transfer-Encoding:chunked Vary:Accept-Encoding X-Frame-Options:SAMEORIGIN X-UA-Compatible:IE=10 用戶在頁面看到的內容「字符串」(看到頁面效果,因爲瀏覽器解析) 瀏覽器(socket客戶端) 2. www.cnblogs.com(42.121.252.58,80) sk.socket() sk.connect((42.121.252.58,80)) sk.send('我想要xx') 5. 接收 6. 鏈接斷開 博客園(socket服務端) 1. 監聽ip和端口(42.121.252.58,80while True: 用戶 = 等待用戶鏈接 3. 收到'我想要xx'
                4. 響應:「好」 用戶斷開 import socket sock = socket.socket() sock.bind(('127.0.0.1',8080)) sock.listen(5) while True: conn,addr = sock.accept() # hang住
        # 有人來鏈接了
        # 獲取用戶發送的數據
        data = conn.recv(8096) conn.send(b"HTTP/1.1 200 OK\r\n\r\n") conn.send(b'123123') conn.close() 1. Http,無狀態,短鏈接 2. 瀏覽器(socket客戶端) 網站(socket服務端) 3. 本身寫網站 a. socket服務端 b. 根據URL不一樣返回不一樣的內容 路由系統: URL -> 函數 c. 字符串返回給用戶 模板引擎渲染: HTML充當模板(特殊字符) 本身創造任意數據 字符串 4. Web框架: 框架種類: - a,b,c                  --> Tornado - [第三方a],b,c          --> wsgiref -> Django - [第三方a],b,[第三方c]  --> flask, 分類: - Django框架(Web。。。。。。) - 其餘
web 框架本質

衆所周知,對於全部的Web應用,本質上其實就是一個socket服務端,用戶的瀏覽器其實就是一個socket客戶端。html

import socket def handle_request(client): buf = client.recv(1024) client.send("HTTP/1.1 200 OK\r\n\r\n") client.send("Hello, Seven") 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()

 

上述經過socket來實現了其本質,而對於真實開發中的python web程序來講,通常會分爲兩部分:服務器程序應用程序python

服務器程序負責對socket服務器進行封裝,並在請求到來時,對請求的各類數據進行整理。mysql

應用程序則負責具體的邏輯處理。web

爲了方便應用程序的開發,就出現了衆多的Web框架,例如:Django、Flask、web.py 等。sql

不一樣的框架有不一樣的開發方式,可是不管如何,開發出的應用程序都要和服務器程序配合,才能爲用戶提供服務。這樣,服務器程序就須要爲不一樣的框架提供不一樣的支持。數據庫

這樣混亂的局面不管對於服務器仍是框架,都是很差的。對服務器來講,須要支持各類不一樣框架,對框架來講,只有支持它的服務器才能被開發出的應用使用。這時候,標準化就變得尤其重要。flask

咱們能夠設立一個標準,只要服務器程序支持這個標準,框架也支持這個標準,那麼他們就能夠配合使用。瀏覽器

一旦標準肯定,雙方各自實現。這樣,服務器能夠支持更多支持標準的框架,框架也可使用更多支持標準的服務器。服務器

WSGI(Web Server Gateway Interface)是一種規範,它定義了使用python編寫的web app與web server之間接口格式,實現web app與web server間的解耦。app

python標準庫提供的獨立WSGI服務器稱爲wsgiref。

from wsgiref.simple_server import make_server def RunServer(environ, start_response): start_response('200 OK', [('Content-Type', 'text/html')]) return [bytes('<h1>Hello, web!</h1>', encoding='utf-8'), ] if __name__ == '__main__': httpd = make_server('', 8000, RunServer) print("Serving HTTP on port 8000...") httpd.serve_forever()

 

二  自定義Web框架

框架

經過python標準庫提供的wsgiref模塊開發一個本身的Web框架

#!/usr/bin/env python #coding:utf-8
from wsgiref.simple_server import make_server def index(): return 'index'
  
def login(): return 'login'
  
def routers(): urlpatterns = ( ('/index/',index), ('/login/',login), ) return urlpatterns def RunServer(environ, start_response): start_response('200 OK', [('Content-Type', 'text/html')]) url = environ['PATH_INFO'] urlpatterns = routers() func = None for item in urlpatterns: if item[0] == url: func = item[1] break
    if func: return func() else: return '404 not found'
      
if __name__ == '__main__': httpd = make_server('', 8000, RunServer) print "Serving HTTP on port 8000..." httpd.serve_forever()

 

模板引擎

在上一步驟中,對於全部的login、index均返回給用戶瀏覽器一個簡單的字符串,在現實的Web請求中通常會返回一個複雜的符合HTML規則的字符串,因此咱們通常將要返回給用戶的HTML寫在指定文件中,而後再返回。如:

index.html

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <h1>Index</h1>
 
</body>
</html>

 

login.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>

 

 

#!/usr/bin/env python # -*- coding:utf-8 -*-
  
from wsgiref.simple_server import make_server def index(): # return 'index'
    f = open('index.html') data = f.read() return data def login(): # return 'login'
    f = open('login.html') data = f.read() return data def routers(): urlpatterns = ( ('/index/', index), ('/login/', login), ) return urlpatterns def run_server(environ, start_response): start_response('200 OK', [('Content-Type', 'text/html')]) url = environ['PATH_INFO'] urlpatterns = routers() func = None for item in urlpatterns: if item[0] == url: func = item[1] break
    if func: return func() else: return '404 not found'
  
  
if __name__ == '__main__': httpd = make_server('', 8000, run_server) print "Serving HTTP on port 8000..." httpd.serve_forever()

 

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

  • 1)自定義一套特殊的語法,進行替換
  • 2)使用開源工具jinja2,遵循其指定語法

index.html

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <h1>{{name}}</h1>
 
    <ul> {% for item in user_list %} <li>{{item}}</li> {% endfor %} </ul>
 
</body>
</html>

 

 

#!/usr/bin/env python # -*- coding:utf-8 -*-
  
from wsgiref.simple_server import make_server from jinja2 import Template def index(): # return 'index'
  
    # template = Template('Hello {{ name }}!')
    # result = template.render(name='John Doe')
 f = open('index.html') result = f.read() template = Template(result) data = template.render(name='John Doe', user_list=['alex', 'eric']) return data.encode('utf-8') def login(): # return 'login'
    f = open('login.html') data = f.read() return data def routers(): urlpatterns = ( ('/index/', index), ('/login/', login), ) return urlpatterns def run_server(environ, start_response): start_response('200 OK', [('Content-Type', 'text/html')]) url = environ['PATH_INFO'] urlpatterns = routers() func = None for item in urlpatterns: if item[0] == url: func = item[1] break
    if func: return func() else: return '404 not found'
  
  
if __name__ == '__main__': httpd = make_server('', 8000, run_server) print "Serving HTTP on port 8000..." httpd.serve_forever()

 

遵循jinja2的語法規則,其內部會對指定的語法進行相應的替換,從而達到動態的返回內容,對於模板引擎的本質

三  本身開發web框架

實現靜態網站

import socket def f1(request): """ 處理用戶請求,並返回相應的內容 :param request: 用戶請求的全部信息 :return: """ f = open('index.fsw','rb') data = f.read() f.close() return data def f2(request): f = open('aricle.tpl','r',encoding='utf-8') data = f.read() f.close() import time ctime = time.time() data = data.replace('@@sw@@',str(ctime)) return bytes(data,encoding='utf-8') def f3(request): import pymysql # 建立鏈接
    conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='', db='db666') cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) cursor.execute("select id,username,password from userinfo") user_list = cursor.fetchall() cursor.close() conn.close() content_list = [] for row in user_list: tp = "<tr><td>%s</td><td>%s</td><td>%s</td></tr>" %(row['id'],row['username'],row['password']) content_list.append(tp) content = "".join(content_list) f = open('userlist.html','r',encoding='utf-8') template = f.read() f.close() # 模板渲染(模板+數據)
    data = template.replace('@@sdfsdffd@@',content) return bytes(data,encoding='utf-8') def f4(request): import pymysql # 建立鏈接
    conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='', db='db666') cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) cursor.execute("select id,username,password from userinfo") user_list = cursor.fetchall() cursor.close() conn.close() f = open('hostlist.html','r',encoding='utf-8') data = f.read() f.close() # 基於第三方工具實現的模板渲染
    from jinja2 import Template template = Template(data) data = template.render(xxxxx=user_list,user='sdfsdfsdf') return data.encode('utf-8') routers = [ ('/xxx', f1), ('/ooo', f2), ('/userlist.htm', f3), ('/host.html', f4), ] def run(): sock = socket.socket() sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind(('127.0.0.1',8080)) sock.listen(5) while True: conn,addr = sock.accept() # hang住
        # 有人來鏈接了
        # 獲取用戶發送的數據
        data = conn.recv(8096) data = str(data,encoding='utf-8') headers,bodys = data.split('\r\n\r\n') temp_list = headers.split('\r\n') method,url,protocal = temp_list[0].split(' ') conn.send(b"HTTP/1.1 200 OK\r\n\r\n") func_name = None for item in routers: if item[0] == url: func_name = item[1] break

        if func_name: response = func_name(data) else: response = b"404" conn.send(response) conn.close() if __name__ == '__main__': run()
s1.py
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <h1>用戶登陸</h1>
    <form>
        <p><input type="text" placeholder="用戶名" /></p>
        <p><input type="password" placeholder="密碼" /></p>
    </form>
</body>
</html> index.fsw
index.fsw
<!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>
            <tr>
                <th>1</th>
                <th>root</th>
                <th>root@qq.com</th>
            </tr>
        </tbody>
    </table>
</body>
</html> aricle.tpl
aricle.tpl

實現動態網站

import socket def f1(request): """ 處理用戶請求,並返回相應的內容 :param request: 用戶請求的全部信息 :return: """ f = open('index.fsw','rb') data = f.read() f.close() return data def f2(request): f = open('aricle.tpl','r',encoding='utf-8') data = f.read() f.close() import time ctime = time.time() data = data.replace('@@sw@@',str(ctime)) return bytes(data,encoding='utf-8') def f3(request): import pymysql # 建立鏈接
    conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='', db='db666') cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) cursor.execute("select id,username,password from userinfo") user_list = cursor.fetchall() cursor.close() conn.close() content_list = [] for row in user_list: tp = "<tr><td>%s</td><td>%s</td><td>%s</td></tr>" %(row['id'],row['username'],row['password']) content_list.append(tp) content = "".join(content_list) f = open('userlist.html','r',encoding='utf-8') template = f.read() f.close() # 模板渲染(模板+數據)
    data = template.replace('@@sdfsdffd@@',content) return bytes(data,encoding='utf-8') def f4(request): import pymysql # 建立鏈接
    conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='', db='db666') cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) cursor.execute("select id,username,password from userinfo") user_list = cursor.fetchall() cursor.close() conn.close() f = open('hostlist.html','r',encoding='utf-8') data = f.read() f.close() # 基於第三方工具實現的模板渲染
    from jinja2 import Template template = Template(data) data = template.render(xxxxx=user_list,user='sdfsdfsdf') return data.encode('utf-8') routers = [ ('/xxx', f1), ('/ooo', f2), ('/userlist.htm', f3), ('/host.html', f4), ] def run(): sock = socket.socket() sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind(('127.0.0.1',8080)) sock.listen(5) while True: conn,addr = sock.accept() # hang住
        # 有人來鏈接了
        # 獲取用戶發送的數據
        data = conn.recv(8096) data = str(data,encoding='utf-8') headers,bodys = data.split('\r\n\r\n') temp_list = headers.split('\r\n') method,url,protocal = temp_list[0].split(' ') conn.send(b"HTTP/1.1 200 OK\r\n\r\n") func_name = None for item in routers: if item[0] == url: func_name = item[1] break

        if func_name: response = func_name(data) else: response = b"404" conn.send(response) conn.close() if __name__ == '__main__': run() s1.py
s1.py
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <h1>用戶登陸</h1>
    <form>
        <p><input type="text" placeholder="用戶名" /></p>
        <p><input type="password" placeholder="密碼" /></p>
    </form>
</body>
</html> index.fsw
index.fsw
<!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>
            <tr>
                <th>1</th>
                <th>@@sw@@</th>
                <th>root@qq.com</th>
            </tr>
        </tbody>
    </table>
</body>
</html> aricle.tpl
aricle.tpl
<!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 row in xxxxx %} <tr>
                    <td>{{row.id}}</td>
                    <td>{{row.username}}</td>
                    <td>{{row.password}}</td>
                </tr> {% endfor %} </tbody>
    </table> {{user}} </body>
</html> userlist.html
userlist.htmlWeb
相關文章
相關標籤/搜索