本文介绍了从Flask的另一条路线中调用路线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找出在烧瓶应用程序中将数据导入到我的模板中的最佳方法。我有两个路线,一个显示索引页,另一个只是返回json。我正试图找出最佳的方式来访问这些信息。目前我有以下路线:

$ p $ jsonObj = module.queryExternalApi()

@ app.route (/)
def index(chapi = jsonObj):
data = getData()
返回render_template('index.jade',chapi = chapi)


@ app.route(/ data / dashboard0)
def getData():
返回jsonify(jsonObj)

在这种情况下,我只是调用获取数据的模块,在本地运行它,但是我想在中显示数据@app .route('/ data / dashboard0')并从那里获得(以及任何新的数据)。有没有办法从另一个URL调用一个url,或者我正在做这个错误的方式吗?

解决方案

是的,这是错误的方法。一般来说,在网页框架中,最好把路线想象成整个页面。但是这并不是说你不能从该路由处理程序中调用多个函数。所以在你的情况下,我会建议移动你的json代码到它自己的函数中,如果你需要,你可以从两个路由中调用。


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?

解决方案

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.

这篇关于从Flask的另一条路线中调用路线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 11:30