python 使用 wsgiref 手撸web 框架


1. 入口文件, 负责启用服务, 转发请求

from wsgiref.simple_server import make_server
from urls.urls import urls


def run(env, response):
    """
        env: 请求相关的数据
        request: 响应相关的数据
        return: 返回给用户端的数据
    """
    request_path = env.get("PATH_INFO")
    func = None
    if request_path in urls:
        func = urls[request_path]
    elif '.css' in request_path or '.js' in request_path:
        func = urls['/static_file']
    if func:
        response('200 OK', [])
        return_str = func(env)
        return [return_str.encode('utf-8')]
    else:
        response('200 OK', [])
        return [b'404 NOT FOUND']


if __name__ == '__main__':
    server = make_server("127.0.0.1", 8888, run)
    server.serve_forever()

2. urls.py 负责将请求地址和对应的处理函数关联起来

from views.views import *

urls = {
    "/index": index,
    "/hello": hello,
    "/book_manage": book_manage,
    '/static_file': static_file
}

3. views.py 处理函数, 负责处理对应的请求

from myutils.db import db
from jinja2 import Template


def index(env):
    return "index"


def hello(env):
    with open('templates/hello.html', 'r', encoding="utf-8") as f:
        return f.read()


def book_manage(env):
    with open('templates/book_manage.html', 'r', encoding="utf-8") as f:
        conn, cursor = db()
        sql = "select * from tb_books"
        cursor.execute(sql)
        result = cursor.fetchall()
        html = Template(f.read()).render(books=result)
        return html


def static_file(env):
    request_filt_path = env.get("PATH_INFO")[1:]
    with open("templates/" + request_filt_path, 'r', encoding="utf-8") as f:
        return f.read()

4. db.py 一个工具方法, 没封装成类

def db():
    import pymysql
    conn = pymysql.connect(host="127.0.0.1",
                           user="root",
                           passwd="yyjeiq",
                           database="fmg",
                           charset="utf8")

    cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
    return conn, cursor

5. templates 下面的 book_manage.html, 静态文件, 使用 jinja2 动态获取数据库的 books


"en">


    "UTF-8">
    "X-UA-Compatible" content="IE=edge">
    "viewport" content="width=device-width, initial-scale=1.0">
    图书管理系统
    "stylesheet" href="./css/bootstrap.min.css">
    
    
    



    
class="container_fluid">
class="container_fluid">
class="row" style="margin: 0;">
class="col-md-9">
class="panel panel-primary">
class="panel-heading">图书列表
class="row" style="padding: 12px;">
class="col-md-5" style="margin: 12px;">
class="input-group"> "text" class="form-control" placeholder="Search for..."> class="input-group-btn">
class="table_box" style="padding: 30px;"> class="table table-hover table-border"> {% for i in books %} {% endfor %}
id 书名 作者 出版社
{{ i.id }} {{ i.name }} {{ i.author }} {{ i.isbn }}

6. 数据库内容

7. 访问结果

最后bb一句: bootstrap YYDS