flask中的url_for与render_template()函数

flask.url_for(endpoint,**values):为给定的endpoint建立URL。html

endpoint:函数名称前端

**values:未知的变量将添加到URL中做为查询参数flask

如:app

 

>>> from flask import Flask, url_for函数

>>> app = Flask(__name__)url

>>> @app.route('/')htm

... def index():it

      pass...test

>>> @app.route('/login')import

... def login():

      pass...

>>> @app.route('/user/<username>')

... def profile(username): 

      pass...

>>> with app.test_request_context():

... print url_for('index')

... print url_for('login')

... print url_for('login', next='/')

... print url_for('profile', username='John Doe')

...

    /

    /login?next=/

    /user/John%20Doe

为了以防blueprints是active,能够在endpoint前加一个"." url_for('.index')

 

test_request_context(*args, **kwargs):建立一个WSGI环境

render_template(template_name_or_list, **context):根据上下文渲染模版

template_name_or_list:须要渲染的模版名或迭代器(其第一个模版名将被渲染)

context:做为参数传递给模版(前端网页)的变量。

如:

from flask import render_template

@app.route('/hello/')

@app.route('/hello/<name>')

def hello(name=None):

     return render_template('hello.html', name=name)

相关文章
相关标签/搜索