我如何将烧瓶URL的一部分设置为Python变量



我只是想知道如何将python烧瓶网址的一部分设置为python变量。

Python代码

from flask import Flask
app = Flask(__name__)
@app.route('/<variable>')
def test(variable):
    test = variable
    return("Hello World!!")
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0')

我不是100%确定您的意思,而是使用烧瓶的动态URL

@app.route('/study_type/')
@app.route('/study_type/<study>')
def study_type(study=None):
    if study == '1':
        return render_template('1.html')
    elif study == '2':
        return render_template('2.html')
    else:
        return render_template('study_type.html')

在此示例中,用户转到/study_type/1,他们被重定向到1.html。如果他们只是击中/study_type,则将重定向到study_type.html。您可以在路由/视图函数中传递动态URL值

您可以使用(在示例中)打印出变量:

return("Hello World!! " + variable)   

print(variable)

或者您可以将其返回到模板:

if study == '1':
    return render_template('1.html', study_no=study)  

,然后将其作为study_no

在您的Jinja模板中可用

我不确定我是否完全遵循您的问题,但是如果您只是想从路由到函数的变量。这里有一些示例http://exploreflask.com/en/latest/views.html#url-converters

取决于可以在路由中输入的变量类型。例如

@app.route('/user/id/<int:user_id>')
def profile(user_id):
    pass

相关内容

最新更新