问题
I am trying to figure out the best way to get data into my template in a flask app. I have two routes, one to display the index page, and another that just returns json. I am trying to figure out the best way to access this information. Currently I have the following routes:
jsonObj = module.queryExternalApi()
@app.route("/")
def index(chapi=jsonObj):
data = getData()
return render_template('index.jade', chapi=chapi)
@app.route("/data/dashboard0")
def getData():
return jsonify(jsonObj)
In this case I just call the module which gets the data which is fine for running it locally, but I want to expose that data in @app.route('/data/dashboard0')
and get it from there (and any new data down the line). Is there a way to call one url from another, or am I going about this the wrong way?
回答1:
Yes, this is the wrong approach. Generally with web frameworks it's best to think of a route as serving up the whole of a page. But that's not to say that you can't call multiple functions from within that route handler. So in your case I would recommend moving your json code into its own function, which you can call from both routes if you need to.
来源:https://stackoverflow.com/questions/33319161/call-a-route-from-within-another-route-in-flask