Reputation: 401
I have started learning flask for web development and experimenting with it since I have a website in mind I would like to create.
My thought has been to create a homepage showing some data that will be updated using cURL or the requests python library. I have some other python code that generates the data to be displayed and I would like to use the POST request for sending a dictionary with the generated information to the server and update the homepage with that new info.
A rather simplistic but comprehensive version of what I have tried so far:
from flask import Flask, redirect, url_for, render_template, request
app = Flask(__name__)
@app.route("/", methods=["POST", "GET"])
def home():
if request.method == "POST":
data = request.form["data"]
return render_template("index.html", content=data)
else:
return render_template("index.html", content="initial_data")
if __name__ == "__main__":
app.run(debug=True)
The code for index.html
<!doctype html>
<html>
<head>
<title>Home Page</title>
</head>
<body>
{{content}}
</body>
</html>
So I would like to send a POST request with some new data to the server and update the webpage with that new data.
import requests
payload = {'data': 'new_data'}
r = requests.post("http://localhost:5000/", data=payload)
All of the above doesn't succeed in updating the data in the webpage when I send a request, it just stays the same. Am I totally off course? Is this even possible in the way I have thought of?
Any comment is much appreciated, thank you.
Upvotes: 0
Views: 310
Reputation: 13170
data
is staying the same because it's being reassigned each time as a local variable. When a POST request happens, the variable is created, passed to the template, then destroyed as it goes out of scope.
Try this as an experiment in showing how a variable might persist between page loads, though only until the server restarts:
from flask import Flask, redirect, url_for, render_template, request
app = Flask(__name__)
app_state = {
'data': 'Initial Data'
}
@app.route("/", methods=["POST", "GET"])
def home():
if request.method == "POST":
app_state['data'] = request.form['data']
return render_template("index.html", content=app_state['data'])
if __name__ == "__main__":
app.run(debug=True)
In that example, you're creating a global dictionary, app_date
, and updating a key on it every time the user sends a POST request to /
with a form payload of data
.
Then, we return the template with the content of the dictionary item.
Upvotes: 1