1

I load CSV data in the React.js front-end using FileReader:

import React, { Component } from 'react';
import { CsvToHtmlTable } from 'react-csv-to-table';
import ReactFileReader from 'react-file-reader';
import Button from '@material-ui/core/Button';

const sampleData = `
NUM,WAKE,SIBT,SOBT
1,M,2016-01-01 04:05:00,2016-01-01 14:10:00
2,M,2016-01-01 04:05:00,2016-01-01 14:10:00
3,M,2016-01-01 04:05:00,2016-01-01 14:10:00
`;

class CSVDataTable extends Component {

    state={
      csvData: sampleData
    };

    handleFiles = files => {
        var reader = new FileReader();
        reader.onload =  (e) => {
          // Use reader.result
          this.setState({
            csvData: reader.result
          })
          this.props.setCsvData(reader.result)
        }
        reader.readAsText(files[0]);
    }

    render() {
        return <div>
          <ReactFileReader
            multipleFiles={false}
            fileTypes={[".csv"]}
            handleFiles={this.handleFiles}>
            <Button
                variant="contained"
                color="primary"
            >
                Load data
            </Button>

          </ReactFileReader>
          <CsvToHtmlTable
            data={this.state.csvData || sampleData}
            csvDelimiter=","
            tableClassName="table table-striped table-hover"
          />
    </div>
    }
}

export default CSVDataTable;

Then I should send csvData to the backend. What is a proper way to do it?

I tried to send csvData, but then it cannot be properly parsed in the backend. I assume that \n is incorrectly encoded, when csvData arrives to the backend:

fetchData = () => {
      const url = "http://localhost:8000/predict?"+
        '&wake='+this.state.wake+
        '&csvData='+JSON.stringify(this.state.csvData);

      fetch(url, {
        method: "POST",
        dataType: "JSON",
        headers: {
          "Content-Type": "application/json; charset=utf-8",
        }
      })
      .then((resp) => {
        return resp.json()
      })
      .then((data) => {
        this.updateDelay(data.prediction)
      })
      .catch((error) => {
        console.log(error, "catch the hoop")
      })
  };

How do you suggest me to send csvData? It looks like JSON.stringify(this.state.csvData) does something wrong. Please help me solving this issue. Thanks.

Update:

I tried this:

  fetchData = () => {
      fetch("http://localhost:8000/predict", {
        method: "POST",
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          wake: this.state.wake,
          csvData: this.state.csvData
        })
      })
      .then((resp) => {
        return resp.json()
      })
      .then((data) => {
        this.updateDelay(data.prediction)
      })
      .catch((error) => {
        console.log(error, "catch the hoop")
      })
  };

But then I cannot receive data in Django backend (Python):

print(request.POST)

Output:

<QueryDict: {}>

or:

print(request.POST['csvData'])

Output:

django.utils.datastructures.MultiValueDictKeyError: 'csvData'

Or:

body_unicode = request.body.decode('utf-8')
body = json.loads(body_unicode)
content = body['csvData']

print("content",content)

Output:

raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

ScalaBoy
  • 3,254
  • 13
  • 46
  • 84
  • 1
    `How do you suggest me to send csvData?` : in the body request – samb102 Feb 22 '19 at 22:09
  • @samb102: What do you mean? Sorry, I am quite new in these topics. I you give an example or a web link, I'd appreciate. Thanks. – ScalaBoy Feb 22 '19 at 22:13
  • Of course, my bad, sorry. Just set a `body` attribute in `fetch` 2nd parameter's object and put `JSON.stringify(this.state.csvData)` as value. See https://stackoverflow.com/questions/29775797/fetch-post-json-data – samb102 Feb 22 '19 at 22:15
  • @samb102: Ok, I see. But how should I retrieve the data from `body` in the backend (Python)? I tried `request.GET.get('csvData')`, but it didn't work. – ScalaBoy Feb 22 '19 at 22:25
  • Sorry I don't know how are handled requests in Python. But see this : https://stackoverflow.com/questions/464040/how-are-post-and-get-variables-handled-in-python – samb102 Feb 22 '19 at 22:29

1 Answers1

0

in your edit you are setting the content-type to application/json but sending a string in it.

body: JSON.stringify({
      wake: this.state.wake,
      csvData: this.state.csvData
})

Try changing this to

body: {
   wake: this.state.wake,
   csvData: this.state.csvData
}
sygmus1897
  • 41
  • 4