When getting from data in Flask, can I somehow bind html elements and their values to an object without using Jinja templating.
Or do I have to send the data via a manual HTTP Post?
When getting from data in Flask, can I somehow bind html elements and their values to an object without using Jinja templating.
Or do I have to send the data via a manual HTTP Post?
I think what you are really asking is "given a client-side JavaScript object, how can I serialize it so that I can easily access the data server-side". If that is your question, there are two ways to do so:
The way you provided in your answer, serializing your object as JSON and submitting it as the body of your POST request:
@app.route("/user", methods=("POST",))
def save_user():
data = request.get_json()
# ... etc. ...
Using FormData
on the client side:
var yourUser = {
firstname: "Joe",
lastname: "Smith",
email: "joe@smith.com",
password: "12345"
};
var formData = new FormData();
Object.keys(yourUser).forEach(function(key) {
formData.append(key, yourUser[key]);
});
// Post formData back to your controller using XHR
combined with the normal request.form
access on the server side:
@app.route("/user", methods=("POST",))
def save_user():
data = request.form
# ... etc. ...
Solve the issue with this
@app.route('/post/user',methods=['POST','GET'])
def saveuser():
data = json.loads(request.data)
firstname = data['firstname']
newuser = User(firstname,lastname,email,password)
db.session.add(newuser)
db.session.commit()
first I get the json string from request.data, then i parse it into a dict and save it to my db