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"
CodePudding user response:
I'll just reenumerate what I know to pass from front-end to backend.
- 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 */,
})
- 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"
- 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"]
request.args (Flask request.args.get get all params (Python))
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"
CodePudding user response:
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 >
<form action="{{url_for('run')}}" method="POST">
<div >
<div >
<div >
<label >Message: </label>
</div>
<div >
<input type="text" name="msg">
</div>
</div>
</div>
<div >
<div >
<div >
<button >send message</button>
</div>
</div>
</div>
</form>
</div>