web框架
1. web框架的本质:
socket服务端 与 浏览器的通信
2. socket服务端功能划分:
a. 负责与浏览器收发消息(socket通信) --> wsgiref/uWsgi/gunicorn...
b. 根据用户访问不同的路径执行不同的函数
c. 从HTML读取出内容,并且完成字符串的替换 --> jinja2(模板语言)
3. Python中 Web框架的分类:
1. 按上面三个功能划分:
1. 框架自带a,b,c --> Tornado
2. 框架自带b和c,使用第三方的a --> Django
3. 框架自带b,使用第三方的a和c --> Flask
2. 按另一个维度来划分:
1. Django --> 大而全(你做一个网站能用到的它都有)
2. 其他 --> Flask 轻量级

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()

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() template = Template(data) # 生成模板文件 # 从数据库中取数据 import pymysql conn = pymysql.connect( host="127.0.0.1", port=3306, user="root", password="123456", database="day59", charset="utf8", ) cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) cursor.execute("select * from userinfo;") user_list = cursor.fetchall() # 实现字符串的替换 ret = template.render({"user_list": user_list}) # 把数据填充到模板里面 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()

<!DOCTYPE html> <html lang="zh-CN"> <head> <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.name}}</td> <td>{{user.pwd}}</td> </tr> {% endfor %} </tbody> </table> </body> </html>