'receive in flask json converted and form data
I have a API in flask. The objetive is to receive a converted csv file (function in javascript) and form data in flask separate. Form data is metadata and csv file converted to json is data. I'm only getting the form data, the json file i'm getting none.
My json converted from csv file it's store in variable result and form data is stored in formdata. I send the two variable separated. I'm receiving all the data that i insert in HTML. The JSON that result from a function that convert csv files to json i'm not getting in flask side.
HTML
<!DOCTYPE html>
<html lang="PT">
<head>
<meta charset="utf-8">
<title>Register</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script type="text/javascript" src="/static/sendform.js"> </script>
<link href="{{url_for('static', filename='css/mainpage.css')}}" rel="stylesheet" type="text/css">
</head>
<body>
<div id="upper_left"></div>
<div id="upper_right"></div>
<div id="lower_left"></div>
<div id="lower_right"></div>
<div class="container">
<div class="title">Metadados - Dados relacionados com o Atleta</div>
<form action="index" method="post">
<div class="user-details">
<div class="input-box">
<span class="details">Nome Completo</span>
<input type="text" name="fullName" placeholder="Introduza o nome completo do atleta">
</div>
<div class="input-box">
<span class="details">Data de Nascimento</span>
<input type="text" name="birthdate" placeholder="Introduza a data de nascimento do atleta">
</div>
<div class="input-box">
<span class="details">Altura</span>
<input type="text" name="height" placeholder="Introduza a altura do atleta em cm">
</div>
<div class="input-box">
<span class="details">Peso</span>
<input type="text" name="weight" placeholder="Introduza o peso do atleta em kg">
</div>
<div class="input-box">
<span class="details">Tamanho da Piscina</span>
<input type="text" name="poolsize" placeholder="Introduza o tamanho da piscina">
</div>
<div class="input-box">
<span class="details">Modalidade</span>
<input type="text" name="modality" placeholder="Introduza a modalidade">
</div>
<div class="input-box">
<span class="details">Estilo(s) de Natação</span>
<input type="text" name="swimStyle" placeholder="Introduza o estilo(s) de natação">
</div>
<div class="input-box">
<span class="details">Género</span>
<select name="gender">
<option value ="gender">Selecionar genéro</option>
<option value ="masculino">Masculino</option>
<option value ="feminino">Feminino</option>
</select>
<div class="input-box">
<span class="details">Escalão Etário</span>
<select name="gender-title">
<option value ="gender-title">Select gender group</option>
<option value ="Escola_de_natacao">ESCOLA DE NATACAO</option>
<option value ="grupos_de_natacao_desportiva">GRUPOS DE FORMACAO DESPORTIVA</option>
<option value ="cadeteA">CADETES A</option>
<option value ="cadeteB">CADETES B</option>
<option value ="infatilB">INFANTIS B</option>
<option value ="infatilA">INFANTIS A</option>
<option value ="juvenilB">JUVENIS B</option>
<option value ="juvenilA">JUVENIS A</option>
<option value ="junior">JUNIORES</option>
<option value ="senior">SENIORES</option>
</select>
</div>
<div class="title">Metadados Envio de dados</div>
<div class="input-box">
<span class="details">Utilizador Id</span>
<input type="text" name="userId" placeholder="Introduza o seu Id">
</div>
<div class="input-box">
<span class="details">Token</span>
<input type="text" name="token" placeholder="Introduza o token">
</div>
<p>Selecionar o ficheiro localmente:</p>
<input name="myFile" type="file" accept=".txt,.xlsx, .xls, .csv" >
<div class="button">
<input type="submit" id="btn-post" value="Enviar dados" onclick="do_ajax();">
<div class="input-box"></dix>
</div>
</div>
</form>
</div>
</body>
</html>
Javascript
function do_ajax() {
var input = document.querySelector('input').files;
if(!input.length){
alert("No file selected");
return;
}
var file = input[0];
var reader = new FileReader();
reader.onload = (function() {
return function(e) {
var fileData = e.target.result.trim().split('\n').map(row => row.split(','));
var HEADERS = ["time", "yaw", "pitch", "roll", "heading", "ax", "ay", "az", "gx", "gy", "gz", "mx", "my", "mz"];
const RESULT = {};
// Assign every heading to the result.
for (const HEADING of HEADERS) RESULT[HEADING] = [];
fileData.map(row =>
// Each row → each column, number of columns === number of headers
row.map((column, i) =>
RESULT[HEADERS[i]]
.push(Number(column))
));
console.log(RESULT);
};
})(file);
reader.readAsText(file);;
let fullName = document.getElementById('fullName').value;
let birthdate = document.getElementById('birthdate').value;
let height = document.getElementById('height').value;
let weight = document.getElementById('weight').value;
let poolsize = document.getElementById('poolsize').value;
let modality = document.getElementById('modality').value;
let swimStyle = document.getElementById('swimStyle').value;
var tel = document.getElementById('gender').value;
var sel = document.getElementById('gender-title').value;
console.log(sel.value);
const formdata = new FormData();
formdata.append("fullName", fullName)
formdata.append("birthdate",birthdate)
formdata.append("weight",weight)
formdata.append("height",height)
formdata.append("poolsize",poolsize)
formdata.append("modality",modality)
formdata.append("swimStyle",swimStyle)
formdata.append("gender",tel)
formdata.append("gender-title",sel)
var xhr = new XMLHttpRequest();
xhr.open('POST', '/index', true);
xhr.send(formdata);
xhr.send(JSON.stringify(RESULT));
};
FLASK
from flask import Flask, request, render_template
import pymongo
import json
app = Flask(__name__)
app.debug = True
@app.route('/', methods=['GET', 'POST'])
@app.route('/index', methods=['GET', 'POST'])
def index():
if request.method == "POST":
name = request.form["fullName"]
birthdate =request.form["birthdate"]
poolsize =request.form["poolsize"]
height =request.form["height"]
weight =request.form["weight"]
modality =request.form["modality"]
swimStyle =request.form["swimStyle"]
gender = request.form["gender"]
gender_title = request.form["gender-title"]
output = request.get_json()
print(output)
print (name,birthdate,poolsize,height,weight,modality,swimStyle)
alldata = { "sessionData": output,
"metadata":{ "birthdate": birthdate, "Name": name,
"Weight": height,"Pool_size":poolsize,
"Weight":weight,"Gender":gender,"Gender_title":gender_title,
"modality":modality, "swimStyle": swimStyle}}
return alldata,200
else:
return render_template('index.html')
if __name__ == "__main__":
app.run()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
