Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Flask,将dataframe作为JSON传递给客户端以显示它_Python_Reactjs_Pandas_Csv_Flask - Fatal编程技术网

Python Flask,将dataframe作为JSON传递给客户端以显示它

Python Flask,将dataframe作为JSON传递给客户端以显示它,python,reactjs,pandas,csv,flask,Python,Reactjs,Pandas,Csv,Flask,我的场景如下:客户端将CSV上传到Flask服务器,Flask将CSV转换为数据帧以执行任务,然后将其作为JSON对象发送回,最后客户端将结果显示在一个 我的问题是:对象作为React子对象无效(找到:具有键{label,text}的对象)。如果要呈现子对象集合,请改用数组。 因此,经过一些研究,我了解到问题来自我将数据从Flask传输到客户机的方式 这是我的代码: @app.route('/analyse_dataset', methods=['GET','POST']) def analys

我的场景如下:客户端将CSV上传到Flask服务器,Flask将CSV转换为数据帧以执行任务,然后将其作为JSON对象发送回,最后客户端将结果显示在一个

我的问题是:
对象作为React子对象无效(找到:具有键{label,text}的对象)。如果要呈现子对象集合,请改用数组。

因此,经过一些研究,我了解到问题来自我将数据从Flask传输到客户机的方式

这是我的代码:

@app.route('/analyse_dataset', methods=['GET','POST'])
def analyse_dataset_route():
    print('/analyse_dataset called', file=sys.stderr)
    try:

        # check if the post request has the dataset part
        if 'file' not in request.files:
            data = {'error': 'Dataset not in requested files'}
            return Response(data, status=400, mimetype='application/json')
        
        print('request.files : ' + str(request.files))
        uploaded_file = request.files['file']

        # no dataset
        if uploaded_file.filename == '':
            logger.debug('Dataset not found, returning to /')
            return redirect('/')

        # dataset ok
        if uploaded_file:

            uploaded_file.stream.seek(0)                   
            df = pd.read_csv(uploaded_file)
            print(df.shape,file=sys.stderr)
            for index, row in df.iterrows():
                print((row['label'], row['text']), file=sys.stderr)
                
            df = df.loc[:, ~df.columns.str.contains('^Unnamed')]                
            print(dumps(df),file=sys.stderr)
            return Response(dumps(df), status=200, mimetype='application/json')
            
        else:
            data = {'error': 'Something went wrong...'}
            return Response(data, status=400, mimetype='application/json')
            
    except Exception as e:
        data = {'error': 'An error occurred while analysing dataset'}
        return Response(data, status=400, mimetype='application/json')
然后我的前端是ReactJS,下面是
App.js
code,我在这里调用Flask函数:

onClickHandler = () => {
        if (this.state.selectedFile == null) {
            toast.error('No file selected')
        } else {
            const data = new FormData()
            data.append('file', this.state.selectedFile)
            let req = "http://localhost:5001/analyse_dataset"
            
            axios.post(req, data, {
                onUploadProgress: ProgressEvent => {
                    this.setState({
                        loaded: (ProgressEvent.loaded / ProgressEvent.total * 100),
                        loading: true
                    })
                },
            })
                .then(res => { // then print response status
                    console.log("file processed: " + res.data)
                    this.setState({
                        redirect: true,
                        jsondata: res.data
                    })
                })
                .catch(err => { // then print response status
                    console.log(err)
                    this.setState({
                        selectedFile: null,
                        loaded: 0,
                        loading: false
                    })
                    setTimeout(() => {
                        toast.error("Process failed, be sure to upload a correct file.")
                    }, 500)
                })
        }
    }
它也是我存储结果以在
success.js中使用的地方,如下所示:

export default class Success extends React.Component {

    constructor(props) {
        super();
        if (props.location.state) {
            this.state = {
                jsondata: props.location.state.referrer,
                upload: true
            } //put jsons data in state object
            toast.success('Upload success')
        } else {
            this.state = {
                upload: false
            }
        }
    }

    render() {
        if (!this.state.upload) {
            return <Redirect push to={{
                pathname: "/"
            }}/>
        } else return (
            <div className="container">
                <p style={{textAlignVertical: "center", textAlign: "center", fontSize: 30}}> Sentiment analysis done </p>
                <div className="row">
                    <div style={{padding: '50px 300px 100px 300px'}} className="col-md-12 offset-md-12 card">
                        <p style={{textAlignVertical: "center", textAlign: "center", fontSize: 22, color: "green"}}>File processed with success</p>
                        
                    </div>
                </div>
                <p style={{textAlignVertical: "center", textAlign: "center", fontSize: 30, marginTop: '50px'}}>Some infos about the extracted data</p>
                <div className="row">
                    <div className="column">
                        <p style={{textAlign: 'center'}}>
                            {this.state.jsondata}
                        </p>
                    </div>
                </div>
            </div>
        )
    }
}

这取决于您希望如何显示它。如果您只想打印整个对象,只需将其包装在
JSON.stringify

<p style={{textAlign: 'center'}}>
  {JSON.stringify(this.state.jsondata)}
</p>

是的,这是可行的,但我的目标是迭代JSON的每个中心,你能帮我吗?好的,我更新了我的答案。我得到的结果是:
标签,[object object]:0text,[object object object]:1
但是谢谢你的帮助如果你有嵌套的对象,你可能希望
JSON.stringify
第二个循环中的对象,因为这完全取决于
this.state.jsondata的结构。我认为,如果数据的使用者是React应用程序,那么响应应该是iterable结构,以节省多余的工程。是的,我开始认为该结构不是最好的,我在编辑中添加了它
<p style={{textAlign: 'center'}}>
  {JSON.stringify(this.state.jsondata)}
</p>
<p style={{textAlign: 'center'}}>
  {Object.keys(this.state.jsondata.label).map(k => `${k}: ${this.state.jsondata.text[k]}`)}
</p>