Call a route from within another route in Flask [duplicate]

随声附和 提交于 2019-12-11 00:07:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!