利用wsgiref模块解析路径并返回结果,
根据浏览器端不同的路径返回不同的页面,做一个简单的web框架
URL:包括四部分
协议://IP:端口(默认80)/路径?a=1&b=2
'''
# 根据路径的不同返回不同的页面
# http://news.baidu.com/guoji
# http://news.baidu.com/guonei
import socket
sock=socket.socket()
sock.bind(("127.0.0.1",9998))
sock.listen(5)
while 1:
conn,addr=sock.accept()
data=conn.recv(1024)
print(data)
# 按着http请求协议解析数据,返回不同的结果
with open("index.html","rb") as f:
data=f.read()
# 按着http响应协议封装数据
conn.send((b"HTTP/1.1 200 OK\r\n\r\n%s"%data))
conn.close()
wsgiref模块就是基于wsgi协议开发的服务模块,让我们专注于web业务编写。不用去写接收http请求,解析请求,发送请求,这些底层代码。
from wsgiref.simple_server import make_server
# 3、有用户连接之后就执行application 传入参数(environ,start_response)
# 解析数据:environ
# 按着http响应协议封装数据:start_response
def application(environ, start_response):
print(environ) # 字典格式的键值对
# 获取当前的请求路径
path = environ.get("PATH_INFO")
start_response('200 OK', []) # 状态码之间空格不是逗号
# 解析路径根据不同路径返回不同页面
if path == '/login':
with open("login.html", "rb") as f:
data = f.read()
elif path == "/index":
with open("index.html", "rb") as f:
data = f.read()
return [data] # 交由start_response做响应
# 1、类实例化对象,封装了socket
httped = make_server("127.0.0.1", 8080, application)
# 2、等待用户连接 相当于accept
httped.serve_forever()
优化1 封装函数:
# 方案2 还可以在继续优化
def login():
with open("login.html", "rb") as f:
data = f.read()
return data
def index():
with open("index.html", "rb") as f:
data = f.read()
return data
url_patterns = [
("/login", login),
("/index", index),
]
func = None
for item in url_patterns:
if path == item[0]:
func = item[1]
break
if func:
return [func()]
else:
return [b'404!']
优化2:
main.py: 启动文件,封装了socket
1 urls.py: 路径与视图函数映射关系 ---- url控制器
2 views.py 视图函数,固定有一个形式参数:environ -----视图函数,
3 templates文件夹: html文件 -----模板
4 models: 在项目启动前,在数据库中创建表结构 ----- 与数据库相关
main文件
from wsgiref.simple_server import make_server
def application(environ, start_response):
start_response('200 OK', [('Content-Type', 'text/html'),("Charset","utf8")])
# 当前请求路径
path=environ.get("PATH_INFO")
# 方案2:
from urls import url_patterns # 导入url列表
func=None
for item in url_patterns:
if path==item[0]:
func=item[1]
break
if func:
return [func(environ)]
else:
return [b'404!']
httpd = make_server('', 9988, application)
# 开始监听HTTP请求:
httpd.serve_forever()
url文件
from views import *
url_patterns=[
("/login",login),
("/index",index),
("/auth",auth),
("/timer",timer)
]
view文件
def login(environ):
with open("templates/login.html", "rb") as f:
data = f.read()
return data
from urllib.parse import parse_qs
def index(environ):
with open("templates/index.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("utf8")
def auth(request):
try:
request_body_size = int(request.get('CONTENT_LENGTH', 0))
except (ValueError):
request_body_size = 0
request_body = request['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='127.0.0.1', port=3306, user='root', passwd='', db='web_yuan') # db:库名
# 创建游标
cur = conn.cursor()
SQL = "select * from userinfo WHERE NAME ='%s' AND PASSWORD ='%s'" % (user, pwd)
cur.execute(SQL)
if cur.fetchone():
f = open("templates/backend.html", "rb")
data = f.read()
data = data.decode("utf8")
return data.encode("utf8")
else:
return b"user or pwd is wrong"
model文件
import pymysql
#连接数据库
conn = pymysql.connect(host='127.0.0.1',port= 3306,user = 'root',passwd='',db='web_yuan') #db:库名
#创建游标
cur = conn.cursor()
sql='''
create table userinfo(
id INT PRIMARY KEY ,
name VARCHAR(32) ,
password VARCHAR(32)
)
'''
cur.execute(sql)
#提交
conn.commit()
#关闭指针对象
cur.close()
#关闭连接对象
conn.close()