网站首页 > 知识剖析 正文
上题目:
接昨天:https://www.toutiao.com/article/7125986007236936226/
昨天解决了前端界面格式化的问题,今天完成把json格式转化为excel表格,并供后端下载挑战。
之前的背景材料:
0. 总体架构设计:https://www.toutiao.com/article/7113727029614215719/
1. 后端架构设计和代码调试 https://www.toutiao.com/article/7115668110866137600/
2. https://www.toutiao.com/article/7116738277759386112/
3. https://www.toutiao.com/article/7117065496683741709/
4. https://www.toutiao.com/article/7120816663796236841/
5. https://www.toutiao.com/article/7121250227876594191/
6. https://www.toutiao.com/article/7125986007236936226/
今天主要做了几块:
- 如何利用flask 框架+pandas 处理字典(json格式)及List,把内容转化为excel表格。
- 如何利用flask 框架 把数据传递给客户端供下载。--用sendfile()函数完成操作。
- 如何在前端html 里面提交POST请求,及GET请求,--用Jquery 里ajax来完成。
做下来之后,感觉前端文件的格式化,及处理还是蛮麻烦的,至少利用js+flask 做多个复杂的处理,今天和一位同学交流,他介绍可以用VUE框架,直接带了Flask 接口+JS函数,可以完成前端的相关文件处理,这样可以降低前端编写的复杂度,而且VUE支持多个不同的客户端(pc ,web等)-- by 飞霜
- 使用flask 框架+panda 处理字典及List,
引入pandas:
1)import pandas as pd
2)mac pip3 安装插件 openpyxl
3)编写相关的处理脚本:
@app.route('/getexcel',methods=['POST'])
def get_excel():
exceldic= request.get_json()
print(exceldic) #print(json_excel) debug
print(type(exceldic)) #print(type(json_excel)) debug
#json_excel= json.dumps(exceldic) debug
if isinstance(exceldic,dict): #字典则外面加括号
df=pd.DataFrame([exceldic]) # converting a python dictionary to pandas dataframe
df.to_excel('./datafile.xlsx', index=False)
elif isinstance(exceldic,list): #队列则直接放入
df = pd.DataFrame(exceldic) # converting a python dictionary to pandas dataframe
df.to_excel('./datafile.xlsx',index=False)
info = "the info is ready to be stored"
return jsonify("info",info)
主要含义,根据前端html 传入的数据做判断,如果是dic 字典,或者list 做相关的转化操作。
- 如果exceldic是字典:df=pd.DataFrame([exceldic])
- 如果exceldic是队列:df=pd.DataFrame(exceldic)
详细函数的使用方法参考:https://www.marsja.se/how-to-convert-json-to-excel-python-pandas/
2.如何利用flask 框架 把数据传递给客户端供下载。--用sendfile()函数完成操作。
使用flask里面的send_file()函数传递文件到html 客户端
@app.route('/download',methods=['GET'])
def download():
if request.method == "GET":
path = "./datafile.xlsx"
return send_file(path,as_attachment=True)
参考文档:
https://www.codegrepper.com/code-examples/python/how+to+make+downloadable+file+in+flask
3.使用ajax 做前端数据的传递:
在script 之间输入doPost() 函数,调用ajax 进行数据POST 传递,同时如果数据传递成功(success)后跳转到download 链接,直接下载生成的excel表格。
function doPost(url)
{
list2={{info|tojson}}
url = "http://127.0.0.1/getexcel"
var val1 = "luke"
var val2 = "test"
var jsondoc = {"key1":val1, "key2":val2}
//var val1 = document.getElementsByName("key1").value;
//var val2 = document.getElementsByName("key2").value;
//$.post(url, {"key1":val1, "key2":val2});
$.ajax({
type:"POST",
url:url,
async:false,
data:JSON.stringify(list2),
contentType:"application/json",
success:function()
{
window.location.href="http://127.0.0.1/download";
}
});
}
具体ajax 相关操作,参考这里:
https://stackoverflow.com/questions/5570747/jquery-posting-json
做跳转的语法:
window.location.href="http://127.0.0.1/download";
详细ajax 相关语法:
https://www.yisu.com/zixun/622811.html
上详细的代码:
客户端flask 代码:57-56clientsidev2.py
from flask import Flask,render_template,request,url_for,redirect,send_file,jsonify
from datetime import date
import requests
import json
import time
import pandas as pd
""" 接:
0. 总体架构设计:https://www.toutiao.com/article/7113727029614215719/
1. 后端架构设计和代码调试 https://www.toutiao.com/article/7115668110866137600/
2. https://www.toutiao.com/article/7116738277759386112/
3. https://www.toutiao.com/article/7117065496683741709/
"""
app = Flask(__name__)
"""
插入逻辑+展示逻辑
"""
@app.route('/',methods=['GET','POST'])
def index():
# 如果提交表单,则收集表单数据,转换为字典数据后,向后端传递
if request.method == "POST":
# 1.收集表单数据
name = request.form['name']
sn = request.form['sn']
value = request.form['value']
# 2.向后端提交post 请求,模拟postman
url = "http://127.0.0.1:8008/api/input"
r=requests.post(url,json={"name":name,"sn":sn,"value":value})
# 3. 把后端请求的返回,做相关展示
info= r.json()
print(info)
print(type(info))
#.4. 把内容做一个展示
return render_template('index.html',name=name,sn=sn,value=value,info=info)
# 如果是输入,则进入输入选项,这里可以输入Name,Serial Number,Value
if request.method == "GET":
return render_template('index.html')
"""
查询逻辑
"""
@app.route('/query',methods=['GET','POST'])
def info_query():
#如果是post请求,直接开始和后端对接并进行查询
if request.method == "POST":
#1. 收集表单请求
searchstring = request.form['searchstring']
#2. 向后端提交Post请求,模拟postman
url = "http://127.0.0.1:8008/api/query"
r = requests.post(url,json={"searchstring":searchstring})
#3. 把后端的结果做解析
info = r.json()
print(info[1])
print(type(info[1]))
#4. 把内容做展示
return render_template('query.html',info=info)
#如果是get请求,则做查询,则跳转到查询页面,输入query name的相关数值
if request.method == "GET":
return render_template('query.html')
"""
展示逻辑
"""
@app.route('/display',methods=['GET'])
def info_display():
url = "http://127.0.0.1:8008/api/display"
r = requests.post(url)
info = r.json()
print(info[1])
print(type(info[1]))
return render_template('display4.html',info=info[1])
@app.route('/getexcel',methods=['POST'])
def get_excel():
exceldic= request.get_json()
print(exceldic)
print(type(exceldic))
#json_excel= json.dumps(exceldic)
#print(json_excel)
#print(type(json_excel))
# converting a python dictionary to pandas dataframe
#df = pd.read_json(json_excel)
if isinstance(exceldic,dict): #字典则外面加括号
df=pd.DataFrame([exceldic])
df.to_excel('./datafile.xlsx', index=False)
elif isinstance(exceldic,list): #队列则直接放入
df = pd.DataFrame(exceldic)
df.to_excel('./datafile.xlsx',index=False)
info = "the info is ready to be stored"
return jsonify("info",info)
@app.route('/download',methods=['GET'])
def download():
if request.method == "GET":
path = "./datafile.xlsx"
return send_file(path,as_attachment=True)
if __name__ == '__main__':
app.run(host='0.0.0.0',port=80,debug = True)
客户端html 代码:display4.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>display2</title>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
<table border = "1">
<tr>
<th>Serial Number</th>
<th>name</th>
<th>value</th>
</tr>
<tr>
<th id="mysn"> </th>
<th id="myname"> </th>
<th id="myvalue"> </th>
</tr>
</table>
<button onclick="myFunction()">展示首行</button>
<button onclick="listAll()">展示所有</button>
<p id="demo"></p>
<button onclick="doPost()" > 用Ajax生成Excel表格</button>
<script>
function myFunction(){
var carname="Volvo";
var list1 = {{info|tojson}};
document.getElementById("demo").innerHTML=carname;
document.getElementById("mysn").innerHTML=list1[0]["Serial number"];
document.getElementById("myname").innerHTML=list1[0]["name"];
document.getElementById("myvalue").innerHTML=list1[0]["value"];
}
function listAll(){
var list2={{info|tojson}};
document.write("<table border = \"1\">")
document.write("<tr>")
document.write("<th>序列号</th>")
document.write("<th>名字</th>")
document.write("<th>金额</th>")
document.write("<th>下载所有</th>")
document.write("</tr>")
for (var i=0; i<list2.length;i++)
{
document.write("<tr>")
document.write("<th>" + list2[i]["Serial number"] + "</th>");
document.write("<th>" + list2[i]["name"] + "</th>");
document.write("<th>" + list2[i]["value"] + "</th>");
document.write("<th>" + "下载本行" + "</th>");
document.write("</tr>")
}
document.write("</table>")
}
function doPost(url)
{
list2={{info|tojson}}
url = "http://127.0.0.1/getexcel"
var val1 = "luke"
var val2 = "test"
var jsondoc = {"key1":val1, "key2":val2}
//var val1 = document.getElementsByName("key1").value;
//var val2 = document.getElementsByName("key2").value;
//$.post(url, {"key1":val1, "key2":val2});
$.ajax({
type:"POST",
url:url,
async:false,
data:JSON.stringify(list2),
contentType:"application/json",
success:function()
{
window.location.href="http://127.0.0.1/download";
}
});
}
</script>
</body>
</html>
执行效果图:
点击html界面"用Ajax生成Excel表格"
跳转到excel表格:
前端日志:
这里格式还需要美化一下,改天再做。
猜你喜欢
- 2024-11-25 服务器弱口令漏洞上传木马攻击实验
- 2024-11-25 10、Django 新建ipa(通讯录)项目
- 2024-11-25 Vue组件传参:Vue父组件向子组件传参
- 2024-11-25 第5天 | 16天搞定前端,html布局,表格和大块头
- 2024-11-25 如何应用“XML+XSLT”技术分离Web表示层数据和样式
- 2024-11-25 web前端ajax笔记之一
- 2024-11-25 vue3 新特性 computed、watch、watchEffect 看完就会
- 2024-11-25 巧用SqlServer数据库实现邮件自动发送功能
- 2024-11-25 「案例演练」测试器与模板继承
- 2024-11-25 Vue的框架(了解)
- 最近发表
- 标签列表
-
- xml (46)
- css animation (57)
- array_slice (60)
- htmlspecialchars (54)
- position: absolute (54)
- datediff函数 (47)
- array_pop (49)
- jsmap (52)
- toggleclass (43)
- console.time (63)
- .sql (41)
- ahref (40)
- js json.parse (59)
- html复选框 (60)
- css 透明 (44)
- css 颜色 (47)
- php replace (41)
- css nth-child (48)
- min-height (40)
- xml schema (44)
- css 最后一个元素 (46)
- location.origin (44)
- table border (49)
- html tr (40)
- video controls (49)