'Why does my data come from request.form when passing it to the backend in Flask, python?
I've been trying to figure out the best way to pass data from frontend to backend in Flask. The problem is that when receiving data on the back end, the data retrieval came from the request.form['msg'], which doesn't make sense since I didn't really use a form, just an input field. Why did it do this? Is there a better way to retrieve data?
Here's my code. There's also an index.html with <input id='msg'> </input>
jQuery / Javascript:
const message = document.getElementById('msg');
$(document).load('/run', {'msg': message.value}, function(){return 'run complete'})
main.py:
@app.route("/run", methods=["GET", "POST"])
def run():
if request.method == 'POST':
msg = request.form["msg"]
print('msg:', msg)
return "OK"
Solution 1:[1]
I'll just reenumerate what I know to pass from front-end to backend.
1. request.form["name_of_the_input"]
HTML
<form action = "/your_url" method = "POST">
<input type = "text" name = "name_of_the_input" />
<button type = "submit"> Send Data </button>
</form>
Python
@app.route("/your_url")
def your_function():
your_variable = request.form["name_of_the_input"]
2. Ajax/Fetch
JavaScript
fetch(`${window.origin}/your_url`, {
method: "POST",
credentials: "include",
body: JSON.stringify(your_data),
cache: "no-cache",
headers: new Headers({
"content-type": "application/json"
})
})
Python
@app.route("/your_url", methods = ["post"])
def printer():
data = request.get_json()
print(data)
return "hey"
3. Flask-SocketIO (https://flask-socketio.readthedocs.io/en/latest/)
Example code
Python
@socketio.on('receiver')
def message_server(msg):
/* Do something here */
JavaScript
/* You need to load socketio, you can look it up at socket.io, the link above also have instructions */
?let? ?socket? ?=? ?io?(?)
? ?socket?.?emit?(?"receiver"?,? ?{
? ?msg?: ?form?.?value? /* your data */,
? ?}?)
?
4. request.args (Flask request.args.get get all params (Python))
5. Same functionality as above but
Python
@app.route("/hello/<your_variable>")
def your_function(variable):
data = variable
.... ....
So when 127.0.0.1:5000/hello/anything_else
data = "anything _else"
Solution 2:[2]
This would be the easiest way, I hope not to cause confusion, here I show you the code:
In your routes file
main.py
@app.route('/render')
def render():
return render_template('index.html')
@app.route('/render/run', methods=['GET', 'POST'])
def run():
if request.method == 'POST':
message = request.form['msg']
print('msg:', message)
flash('You notification message OK!')
return redirect(url_for('render'))
in your HTML file, postscript use bootstrap )
index.html
<div class="container-fluid pt-3">
<form action="{{url_for('run')}}" method="POST">
<div class="col justify-content-md-center">
<div class="row pt-3">
<div class="col pt-3">
<label class="form-label">Message: </label>
</div>
<div class="col pt-3">
<input class="form-control" type="text" name="msg">
</div>
</div>
</div>
<div class="container pt-3">
<div class="row justify-content-md-center">
<div class="col col-lg-2">
<button class="btn btn-success btn-block rounded">send message</button>
</div>
</div>
</div>
</form>
</div>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | José Valentín |