In the Flask documentation, it gives the following example code:
from flask import make_response
@app.route('/')
def index():
resp = make_response(render_template(...))
resp.set_cookie('username', 'the username')
return resp
Why is it necessary to make a response object? Can’t cookies be set whenever with javascript?
The key insight was that routes expect response objects, so when you to render_template(..) or redirect(url_for(..)) that returns a response object containing your rendered view. It doesn’t really matter that you set the cookie right away, you generally have to return a response on any route anyway, so might as well do it there if it is convenient.