领先的免费Web技术教程,涵盖HTML到ASP.NET

网站首页 > 知识剖析 正文

57challenges-56个挑战-客户端设计(part4)

nixiaole 2024-11-25 15:43:16 知识剖析 15 ℃

上题目:

接昨天: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/

今天主要做了几块:

  1. 如何利用flask 框架+pandas 处理字典(json格式)及List,把内容转化为excel表格。
  2. 如何利用flask 框架 把数据传递给客户端供下载。--用sendfile()函数完成操作。
  3. 如何在前端html 里面提交POST请求,及GET请求,--用Jquery 里ajax来完成。

做下来之后,感觉前端文件的格式化,及处理还是蛮麻烦的,至少利用js+flask 做多个复杂的处理,今天和一位同学交流,他介绍可以用VUE框架,直接带了Flask 接口+JS函数,可以完成前端的相关文件处理,这样可以降低前端编写的复杂度,而且VUE支持多个不同的客户端(pc ,web等)-- by 飞霜

  1. 使用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表格:



前端日志:

这里格式还需要美化一下,改天再做。

Tags:

最近发表
标签列表