Django(wsgiref、jinja2模块使用介绍)

day60

wsgiref比较稳定

"""
根据URL中不同的路径返回不同的内容--函数进阶版
返回HTML页面
让网页动态起来
wsgiref模块版
"""

import time
from wsgiref.simple_server import make_server


# 将返回不同的内容部分封装成函数
def yimi(url):
    with open("yimi.html", "r", encoding="utf8") as f:
        s = f.read()
        now = str(time.time())
        s = s.replace("@@xx@@", now)
    return bytes(s, encoding="utf8")


def xiaohei(url):
    with open("xiaohei.html", "r", encoding="utf8") as f:
        s = f.read()
    return bytes(s, encoding="utf8")


# 定义一个url和实际要执行的函数的对应关系
list1 = [
    ("/yimi/", yimi),
    ("/xiaohei/", xiaohei),
]


def run_server(environ, start_response):
    start_response('200 OK', [('Content-Type', 'text/html;charset=utf8'), ])  # 设置HTTP响应的状态码和头信息
    url = environ['PATH_INFO']  # 取到用户输入的url  不用自己分割
    func = None
    for i in list1:
        if i[0] == url:
            func = i[1]
            break
    if func:
        response = func(url)
    else:
        response = b"404 not found!"
    return [response, ]


if __name__ == '__main__':
    httpd = make_server('127.0.0.1', 8090, run_server)
    print("我在8090等你哦...")
    httpd.serve_forever()

 xiaohei.html、yimi.html和上一节内容相同。

=============================================================================================================================================

jinja2使用到数据库

from wsgiref.simple_server import make_server
from jinja2 import Template


def index():
    with open("09 jinja2版web框架.html", "r", encoding="utf-8") as f:
        data = f.read()#打开html
    template = Template(data)  # 生成模板文件
    # 从数据库中取数据
    import pymysql

    conn = pymysql.connect(
        host="127.0.0.1",
        port=3306,
        user="root",
        password="1×××××8",
        database="userinfo",
        charset="utf8",
    )
    cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
    cursor.execute("select * from info;")
    user_list = cursor.fetchall()
    # 实现字符串的替换
    ret = template.render({"user_list": user_list})#jinja2把数据填充到模板里面 渲染 用后面user_list替换data其中内容
    return [bytes(ret, encoding="utf8"), ]


def home():#用不到
    with open("home.html", "rb") as f:
        data = f.read()
    return [data, ]


# 定义一个url和函数的对应关系
URL_LIST = [
    ("/index/", index),
    ("/home/", home),
]


def run_server(environ, start_response):
    start_response('200 OK', [('Content-Type', 'text/html;charset=utf8'), ])  # 设置HTTP响应的状态码和头信息
    url = environ['PATH_INFO']  # 取到用户输入的url
    func = None  # 将要执行的函数
    for i in URL_LIST:
        if i[0] == url:
            func = i[1]  # 去之前定义好的url列表里找url应该执行的函数
            break
    if func:  # 如果能找到要执行的函数
        return func()  # 返回函数的执行结果
    else:
        return [bytes("404没有该页面", encoding="utf8"), ]


if __name__ == '__main__':
    httpd = make_server('', 8000, run_server)
    print("Serving HTTP on port 8000...")
    httpd.serve_forever()

jinja2版web框架.html

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="x-ua-compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Title</title>
</head>
<body>


<table border="1">
    <thead>
    <tr>
        <th>ID</th>
        <th>用户名</th>
        <th>密码</th>
    </tr>
    </thead>
    <tbody>
    {% for user in user_list %}
    <!--一行-->
    <tr>
        <td>{{user.id}}</td>
        <td>{{user.username}}</td>
        <td>{{user.password}}</td>
    </tr>
    {% endfor %}
    </tbody>
</table>
</body>
</html>

数据库内容:

执行结果:

原文地址:https://www.cnblogs.com/112358nizhipeng/p/10279440.html