DIY一個Web框架

1、前言html

2、框架結構及實現流程python

3、總結mysql

 

1、前言

  當咱們瞭解了Web應用和Web框架,以及HTTP協議的原理以後,咱們能夠本身動手DIY一個最簡單的WEB框架,以加深對Web框架的理解,併爲即將學習的Django探探路。web

 

2、框架結構及實現流程

  1.框架結構的內容以下圖所示

  咱們DIY的這個Web框架按照啓動的前後順序,大體分爲這樣幾個部分,分別是models.py、manage.py、urls.py、views.py、templates(html文件)五個部分,下面咱們分別對這五個部分進行實現,最後,進行運行測試,驗證框架的的可用性。sql

  2.實現流程

  (1) models.py -- 與數據庫相關的,在咱們的項目啓動前,利用models.py在數據庫中建立表結構,注意,僅運行一次。數據庫

#!/usr/bin/env python3
#!-*- coding:utf-8-*-
# write by cc

import pymysql

# 1.創建鏈接
conn = pymysql.connect(
    host = 'localhost',
    port = 3306,
    user = 'cc1',
    password = 'cc111',
    db = 'db1',
    charset = 'utf8'
)

# 2.獲取遊標
cursor = conn.cursor()
# cursor = conn.cursor(pymysql.cursor.DictCursor) # 設遊標類型爲字典類型

# 3.執行sql語句
sql = "create table users(id int,user char(12),pwd char(12))"
rows = cursor.execute(sql)
print(rows) # 打印受影響的記錄條數

# 4.提交(必須提交,才能實現操做)
conn.commit()

# 5.關閉遊標和鏈接
cursor.close()
conn.close()

  (2) manage.py -- 項目的啓動文件app

from wsgiref.simple_server import make_server

from urls import url_list

def application(environ,start_response):
    path = environ.get("PATH_INFO")
    print(path)
    start_response("200 OK",[('Content-Type','text/html')])

    func = None
    for item in url_list:
        if path == item[0]:
            func = item[1]
            break
    if func:
        return [func(environ)]
    else:
        return [b'404 Not found']

if __name__ == '__main__':
    httpd = make_server("",8080,application) # 指定端口
    print('Serving HTTP on port 8080...')
    httpd.serve_forever() # 開啓監聽

  (3) urls.py -- url控制器,反映路徑與視圖函數的映射關係框架

from app01.views import *

url_list = [
    ('/favcion.ico',fav),
    ('/index',index),
    ('/login',login),
    ('/reg',reg),
    ('/timer',timer),
    ('/auth',auth)
]

  (4) views.py -- 視圖函數,固定接收一個形式參數:environsocket

from urllib.parse import parse_qs
def fav(environ):
    with open('templates/favcion.ico','rb') as f:
        data = f.read()
    return data

def index(environ):
    with open('templates/index.html','rb') as f:
        data = f.read()
    return data

def login(environ):
    with open('templates/login.html','rb') as f:
        data = f.read()
    return data

def reg(environ):
    with open('templates/reg.html','rb') as f:
        data = f.read()
    return data

def timer(environ):
    import datetime
    now = datetime.datetime.now().strftime("%y-%m-%d %X")
    return now.encode('utf-8')

def auth(environ):
    try:
        request_body_size = int(environ.get('CONTENT_LENGTH',0))
    except(ValueError):
        request_body_size = 0
    request_body = environ['wsgi.input'].read(request_body_size)
    data = parse_qs(request_body)

    # 解析出用戶輸入的用戶名和密碼
    user = data.get(b'user')[0].decode('utf8')
    pwd = data.get(b'pwd')[0].decode('utf8')


    # 鏈接數據庫
    import pymysql
    conn = pymysql.connect(host='localhost',port=3306,user='cc1',password='cc111',db='db1',charset='utf8')

    # 建立遊標
    cursor = conn.cursor()

    # 執行數據查詢、插入等操做
    sql = 'select * from users where user=%s and pwd=%s'
    cursor.execute(sql,(user,pwd))

    # 驗證是否能取出相關記錄
    if cursor.fetchone():
        print(cursor.fetchone())
        f = open('templates/backend.html','rb')
        data = f.read()
        data = data.decode('utf8')
        return data
    else:
        return b'user or password is wrong'

  (5) templates -- 儲存 html 文件,當用戶輸入的路徑正確存在與url控制器中時,爲用戶展現指定的頁面。函數

  favcion.ico 是一個縮略圖,可自由指定。

  index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>首頁</title>
</head>
<body>
    <h1>Hello world!</h1>
    <h2>Boys and girls!</h2>
    <h3><a href="https://www.cnblogs.com/schut"/>This is my web</a></h3>
    <img src="https://pic.cnblogs.com/avatar/1209144/20170813234607.png">
</body>
</html>

  login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登陸</title>
</head>
<body>
    <h1>Hello world!</h1>
    <h2>Boys and girls!</h2>
    <form action="http://127.0.0.1:8080/auth" method="post">
        姓名<input type="text" name="user">
        密碼<input type="password" name="pwd">
        <input type="submit">
    </form>
</body>
</html>

  reg.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>註冊頁面</title>
</head>
<body>
    <h3>歡迎來到註冊頁面</h3>
    <form action="" method="post">
        用戶名:<input type="text" name="username"><br/>
        密 碼:<input type="password" name="pwd"><br/>
        再次輸入密碼:<input type="password" name="pwd2"><br/>
        <input type="submit">
        <input type="reset">
    </form>
</body>
</html>

  backend.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>index</title>
</head>
<body>
    <h2>歡迎登陸</h2>
</body>
</html>

 

3、總結

  以上DIY的簡易框架,大體能夠分爲五個部分,各自承擔不一樣的做用,缺一不可。

manage.py -- 啓動文件,封裝socket 1 urls.py -- 路徑與視圖函數的映射關係 ------------- url控制器 2 views.py -- 視圖函數,固定接收一個形式參數:environ ------- 視圖函數 3 templates文件夾 -- html文件 -------模板 4 models --在項目啓動前,在數據庫中建立表結構 ----- 與數據庫相關
相關文章
相關標籤/搜索