简体   繁体   English

使用 React 前端和 flask 后端显示 CSV 文件

[英]Displaying a CSV file using react frontend and flask backend

I'm trying to read a csv file using flask and then display it through react (The display part should be compulsorily done through react).我正在尝试使用 flask 读取一个 csv 文件,然后通过 react 显示它(显示部分应该通过 react强制完成)。 I'm stuck at the return part of js file.我被困在 js 文件的返回部分。

This is the flask( .py )code:这是烧瓶( .py )代码:

from flask import Flask,render_template,request
import os
import pandas as pd

app=Flask(__name__)
app.secret_key="123"

app.config["UPLOAD_FOLDER1"]="static/csv"

@app.route("/upload",methods=['GET','POST'])
def upload():
    return render_template("UploadCsv.html")

@app.route("/display",methods=["GET","POST"])
def display():
    upload_file = request.files['upload_csv']
    if upload_file.filename != '':
            file_path = os.path.join(app.config["UPLOAD_FOLDER1"], upload_file.filename)
            upload_file.save(file_path)
            data=pd.read_csv(file_path,sep=",")
            return render_template("CsvContent.html",data=data.to_html(index=False))

if __name__=='__main__':
    app.run(debug=True)

And here are the two HTMLs used in the.py file above: UploadCsv.html这是上面.py 文件中使用的两个 HTML: UploadCsv.html

<html>
    <head>
        <title>Upload CSV File</title>
    </head>
    <body>
        <div class="col-md-offset-3 col-md-5" style="margin-top:70px">
            <form method="POST" action="http://127.0.0.1:5000/display" enctype="multipart/form-data">
                <h3 class="page-header text-primary">Upload CSV File</h3>
                <div class="form-group">
                    <label>Browse CSV File</label>
                    <input type="file" class="form-control" name="upload_csv">
                </div>
                <div class="form-group">
                    <button type="submit" class="btn btn-success btn-block">Upload CSV</button>
                </div>
            </form>
        </div>
    </body>
</html>

CsvContent.html CsvContent.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>CSV File</title>
</head>
<body>
    <h2>Here's your uploaded CSV file :</h2>
    {{data|safe}}
</body>
</html>

This successfully reads and displays the CSV file completely through Flask. Now, here's the catch, I have to integrate react too.这通过 Flask 成功读取并显示了 CSV 文件。现在,问题来了,我也必须集成 React。 And this is where I'm messing up.这就是我搞砸的地方。 Here's my React code, if it helps.这是我的 React 代码,如果有帮助的话。

 const[csvupload,setCsvUpload] = useState()

useEffect(()=> {

  fetch('http://127.0.0.0:5000/display',{

    'method':'POST',

    headers: {

      'Content-Type' : 'application/json'

    }

  })

  .then(resp => resp.json())

  .then(resp => setCsvUpload(resp))

  .catch(error => console.log(error))

},[])

  return (

   

    <Fragment>

      <div className="upload" >

          Upload Your CSV File
       
            <Row md={12}>

                <Col md={6} className="body-upload">

                <input type="file" accept=".csv" onChange={handleFileUpload} multiple />  

                <button onClick={modalOpen}> UPLOAD </button>

                </Col>
            </Row>

            {csvupload.map(csv =>{

              return( 
(**What should be here?**)

                <div>


                </div>

              )

            })}

      </div>

    </Fragment>

  );

};

export default UploadFile;

How can I return the CSV file through react?如何通过反应返回CSV文件? I am using fetch here, is it even the right method?我在这里使用 fetch,它是正确的方法吗? What should I put inside the return method so that when I upload the csv, it should read the file, store in "static/csv" (as given in the flask code) and display the file below before clicking Upload.我应该在 return 方法中放入什么,以便当我上传 csv 时,它应该读取文件,存储在“static/csv”中(如 flask 代码中给出的那样)并在单击上传之前显示下面的文件。 I know its a long question, but please help.我知道这是一个很长的问题,但请帮忙。 Any kinda help would be appreciated and I'm willing to provide information required.任何有点帮助将不胜感激,我愿意提供所需的信息。

Few things you can do:你可以做的几件事:

  1. The call you make to /display has no payload being sent.您对/display的调用没有发送有效负载。 If that is the case, you can change to a GET call如果是这种情况,您可以更改为 GET 调用

  2. Parsing the csv directly on the frontend can be resource intensive depending on the content.根据内容,直接在前端解析 csv 可能会占用大量资源。 It would be better for you to parse it on the backend itself and then send the JSON to react that looks like the following (or any other structure based on your needs):你最好在后端本身解析它,然后发送 JSON 来做出如下所示的反应(或根据你的需要的任何其他结构):

 // option1 { row1: [col1, col2], row2: [col1, col2] } // or send an array of rows // option2 [[col1, col2], [col1, col2]]

  1. Once you have the parsed csv content you can use it like this on react:解析 csv 内容后,您可以像这样在 React 中使用它:

 // option 2 { csvupload.map((row) => { // you can format as per your requirement // col1=row[0] and col2=row[1] return <div>{row}</div>; }) }

 // option 1 { Object.keys(csvupload).map((rowIndex) => { // you can format as per your requirement // col1=csvupload[rowIndex][0] and col2=csvupload[rowIndex][1] return <div>{csvupload[rowIndex]}</div>; }) }

Personally, I feel option 1 would be better.就个人而言,我觉得选项 1 会更好。 But you can change this structure based on whatever best fits your requirements.但是您可以根据最适合您的要求来更改此结构。

Edit: based on comment编辑:基于评论

  1. This answer might help for parsing what to do ,这个答案可能有助于解析要做什么
  2. and the docs for the function used further info in docs function 的文档在文档中使用了更多信息
  3. In option1, Object.keys(csvupload) returns an array of keys.在选项 1 中,Object.keys(csvupload) 返回一个键数组。 rowIndex is an index of this array. rowIndex 是这个数组的索引。 When passed into the csvupload JSON, it returns the column array [col1, col2]当传递到 csvupload JSON 时,它返回列数组[col1, col2]
  4. In option2, row is the array of columns in that specific row [col1, col2] (same as option1)在选项 2 中,行是该特定行中的列数组[col1, col2] (与选项 1 相同)
  5. Both options give the same result.两个选项给出相同的结果。 It's just a difference of how you are accessing the value这只是您访问价值的方式不同

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM