手写web框架

自定义web框架

框架功能

"""
功能视图

用户访问指定url 获取数据库数据,并返回到页面


"""




image-20231109171956354

wsgiref模块

#01 文件结构
"""
urls.py						路由与视图函数对应关系
views.py					视图函数(后端业务逻辑)
templates文件夹		专门用来存储html文件
"""
# 按照功能的不同拆分之后 后续添加功能只需要在urls.py书写对应关系然后取views.py书写业务逻辑即可


服务端

from wsgiref.simple_server import make_server

from urls import urls
from views import *
def run(env, response):
    """
    :param env: 请求数据
    :param response: 响应数据
    :return:
    """
    response('200 OK', [])
    # 获取地址 path
    curr_path = env.get('PATH_INFO')
    func = None
    # 从视图里查找对应关系 返回
    for uri in urls:
        if curr_path == uri[0]:
            print(curr_path,uri)
            func = uri[1]
            break
    # 判断func是否有值 有值则执行函数
    if func:
        res = func(env)
    else:
        res = error(env)
    return [res.encode('utf-8')]


if __name__ == '__main__':
  	#创建监听
    server = make_server('127.0.0.1', 8080, run)
    # 启动函数
    server.serve_forever()

    

路由 urls.py


"""
路由于视图关系

"""

from views import *

urls = [
    ('/index',index),
    ('/login',login),
    ('/error',error),
    ('/xxx',file_tmp),
    ('/get_user',get_user)

]

视图函数 后端处理views.py


"""
视图函数
"""


def index(env):
    return "index hi"


def login(env):
    return "login"


def error(env):
    return "404 error"

# 读取文件
def file_tmp(env):
    with open(r'templates/xxx.html', 'r', encoding='utf-8') as f:
        return f.read()

# 模版语法 通过字典给前端传值
from jinja2 import Template
def get_user(env):
    # 定义字典
    user_dic = {'username': 'futongxue', 'age': 18}
    with open(r'templates/02-get_user.html', 'r', encoding='utf-8') as f:
        data = f.read()
    # 生产模版数据
    tmp = Template(data)
    res = tmp.render(user=user_dic)
    return res

import pymysql
# 数据库交互
def getsql(env):
    # 数据库里获取数据
    conn = pymysql.connect(
        user='root',
        host='192.168.5.9',
        password='0x00NF2001',
        port=3306,
        database='note',
        charset='utf8',
        autocommit=True
    )
    cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
    sql = 'SELECT * FROM `user`;'
    affect_rows = cursor.execute(sql)
    data_dic = cursor.fetchall()
    # 拿取数据 传给前端页面
    with open(r'templates/02-usersql.html', 'r', encoding='utf-8') as f:
        data = f.read()
    # 生产模版数据
    tmp = Template(data)
    res = tmp.render(user_list=data_dic)
    return res


模版语法之Jinja2模块

pip3 install jinja2
"""模版语法是在后端起作用的"""

# 模版语法(非常贴近python语法)
{{ user }}
{{ user.get('username')}}
{{ user.age }}
{{ user['hobby'] }}


{% for user_dict in user_list %}
                        <tr>
                            <td>{{ user_dict.id}}</td>
                            <td>{{ user_dict.username}}</td>
                            <td>{{ user_dict.password}}</td>
                            <td>{{ user_dict.hobby}}</td>
                        </tr>
{% endfor%}

templates 页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="https://cdn.bootcss.com/twitter-bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://cdn.bootcss.com/twitter-bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>

<div class="container">
    <div class="row">
        <div class="col-md-8 col-md-offset-2">
            <h1 class="text-center">用户数据</h1>
            <table class="table table-hover table-striped">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>username</th>
                        <th>password</th>
                        <th>hobby</th>
                    </tr>
                </thead>
                <tbody>
<!--                    [{},{},{},{},{}]-->
                    {% for user_dict in user_list %}
                        <tr>
                            <td>{{ user_dict.id}}</td>
                            <td>{{ user_dict.username}}</td>
                            <td>{{ user_dict.password}}</td>
                            <td>{{ user_dict.hobby}}</td>
                        </tr>
                    {% endfor%}
                </tbody>
            </table>
        </div>
    </div>
</div>

</body>
</html>

image-20231109170606862

posted @   宁采臣open  阅读(15)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· spring官宣接入deepseek,真的太香了~
点击右上角即可分享
微信分享提示