Python Flask Basics Character Builder Starting the Builder

Diem Pham
Diem Pham
12,276 Points

Could anyone please explain the purpose/meaning of function get_saved_data?

@app.route('/') def index(): data = get_saved_data() return render_template('index.html', saves=data)

@app.route('/save', methods=['POST']) def get_saved_data(): try: data = json.loads(request.cookies.get('character')) except TypeError: data = {} return data

I don't understand the purpose of function get_saved_data and why we need data=get_saved_data() in index?

1 Answer

Max Hirsh
Max Hirsh
16,761 Points

I hope this answer isn't too redundant, but my understanding is that "get_saved_data()" is a "GET" function that does what its name describes, namely, retrieving saved data from a cookie. That way, whenever index(): is used, an up to date set of information is stored as the variable "data" in the line "data = get_saved_data()." This is done because the saved data can change over time and we want the program to account for this each time index is loaded. Finally the data variable is passed along to the "index.html" template with the line "render_template('index.html', saves=data)." The reason for this is that the data variable has information that needs to be reflected in how the template is rendered. Hope this explanation helps and let me know if you have any questions!