显示数据库信息及发送Ajax请求
framework.py:
"""web框架的职责专门负责处理动态资源请求"""
import json
import time
import pymysql
route_list=[]
#定义带有参数的装饰器
def route(path):def decorator(func):#装饰器执行的时候就需要把路由添加到路由列表里route_list.append((path, func))def inner():result=func();return resultreturn innerreturn decorator# 获取首页数据
@route("/index.html")
def index():# 状态信息status = "200 OK"# 响应头信息response_header = [("Server", "PWS/1.1")]# 1.打开指定模板文件,读取模板文件中的数据with open("template/index.html","r",encoding='utf-8') as file:file_data=file.read()# 2.查询数据库,模板里面的模板变量替换成以后从数据库里查询的数据conn=pymysql.connect(host="localhost",port=3306,user="root",password="123456",database="stock_db",charset="utf8")#获取游标cursor=conn.cursor()#准备sqlsql="select * from info;"cursor.execute(sql)#获取查询结果result=cursor.fetchall()print(result)cursor.close()# web框架处理后的数据# 遍历每一条数据,完成数据的tr标签封装data=""for row in result:data += """<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td><input type="button" value="添加" id="toAdd" name="toAdd" systemidvaule="000007"></td></tr>""" % rowresponse_body=file_data.replace("{%content%}",data)# 这里返回的是元组return status, response_header, response_body#获取个人中心数据接口
@route("/center_data.html")
def center_data():#从数据库把数据查询处理,然后把查询处理的数据转成json数据#创建连接对象conn=pymysql.connect(host="localhost",port=3306,user="root",password="123456",database="stock_db",charset="utf8")cursor=conn.cursor()sql="select i.code, i.short, i.chg, i.turnover, i.price, i.highs, f.note_info from info i inner join focus f on i.id = f.info_id"cursor.execute(sql)result=cursor.fetchall()print(result)#把元组转成列表字典center_data_list=[{"code":row[0],"short": row[1],"chg": row[2],"turnover": row[3],"price": str(row[4]),"highs":str( row[5]),"note_info":row[6]}for row in result]print(center_data_list)#ensure_ascii=False在控制台能显示中文json_str=json.dumps(center_data_list,ensure_ascii=False)cursor.close()# 状态信息status = "200 OK"# 响应头信息,指定编码格式,因为没有模板文件response_header = [("Server", "PWS/1.1"),("Content-Type","text/html;charset=utf-8")]response_body=json_strreturn status, response_header, response_body#获取个人中心数据
@route("/center.html")
def center():# 状态信息status = "200 OK"# 响应头信息response_header = [("Server", "PWS/1.1")]# 1.打开指定模板文件,读取模板文件中的数据with open("template/center.html","r",encoding='utf-8') as file:file_data=file.read()# 2.查询数据库,模板里面的模板变量替换成以后从数据库里查询的数据# web框架处理后的数据# 获取当前时间,模拟数据库内容# data = time.ctime()response_body=file_data.replace("{%content%}"," ")# 这里返回的是元组return status, response_header, response_body# 处理没有找到的动态资源
def not_found():# 状态信息status = "404 Not Found"# 响应头信息response_header = [("Server", "PWS/1.1")]# web框架处理后的数据data = "not found"# 这里返回的是元组return status, response_header, data# 处理动态资源请求
def handle_request(env):# 获取动态的请求资源路径request_path = env["request_path"]print("动态资源请求的地址:", request_path)# 判断请求的动态资源路径,选择指定的函数处理对应的动态资源请求for path, func in route_list:if request_path == path:result = func()return resultelse:result = not_found()return result# if request_path == "/index.html":# # 获取首页数据# result = index()# # 把处理后的结果返回给web服务器使用,让web服务器拼接响应报文时使用# return result# elif request_path=="/center.html":# #个人中心# result=center()# return result# else:# # 没有动态资源数据, 返回404状态信息# result = not_found()# # 把处理后的结果返回给web服务器使用,让web服务器拼接响应报文时使用# return result
if __name__=="__main__":center_data()
center.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>个人中心 - 个人选股系统 V5.87</title><link href="/css/bootstrap.min.css" rel="stylesheet"><script src="/js/jquery-1.12.4.min.js"></script><script src="/js/bootstrap.min.js"></script><script>$(document).ready(function(){// 发送ajax请求,获取个人中心数据$.get("center_data.html",function (data) {// ajax 成功回调函数// 获取table标签var $table = $(".table");// 如果指定了返回数据的解析方式是json,那么data就是一个js对象for(var i = 0; i < data.length; i++){// 根据下标获取每一个个人中心数据js对象var oCenterData = data[i];// 封装后的每一个tr标签var oTr = '<tr>' +'<td>'+ oCenterData.code +'</td>' +'<td>'+ oCenterData.short +'</td>' +'<td>'+ oCenterData.chg +'</td>' +'<td>'+ oCenterData.turnover +'</td>' +'<td>'+ oCenterData.price +'</td>' +'<td>'+ oCenterData.highs +'</td>' +'<td>'+ oCenterData.note_info +'</td>' +'<td><a type="button" class="btn btn-default btn-xs" href="/update/000007.html"> <span class="glyphicon glyphicon-star" aria-hidden="true"></span> 修改 </a></td>' +'<td><input type="button" value="删除" id="toDel" name="toDel" systemidvaule="000007"></td>' +'</tr>'// 给table标签追加每一行tr标签$table.append(oTr)}}, "json");$("input[name='toDel']").each(function(){var currentAdd = $(this);currentAdd.click(function(){code = $(this).attr("systemIdVaule");alert("/del/" + code + ".html");$.get("/del/" + code + ".html", function(data, status){alert("数据: " + data + "\n状态: " + status);});window.location.reload()});});});</script>
</head><body>
<div class="navbar navbar-inverse navbar-static-top "><div class="container"><div class="navbar-header"><button class="navbar-toggle" data-toggle="collapse" data-target="#mymenu"><span class="icon-bar"></span><span class="icon-bar"></span><span class="icon-bar"></span></button><a href="#" class="navbar-brand">选股系统</a></div><div class="collapse navbar-collapse" id="mymenu"><ul class="nav navbar-nav"><li ><a href="/index.html">股票信息</a></li><li class="active"><a href="">个人中心</a></li></ul></div></div>
</div>
<div class="container"><div class="container-fluid"><table class="table table-hover"><tr><th>股票代码</th><th>股票简称</th><th>涨跌幅</th><th>换手率</th><th>最新价(元)</th><th>前期高点</th><th style="color:red">备注信息</th><th>修改备注</th><th>del</th></tr>{%content%}</table></div>
</div>
</body>
</html>
运行结果: