flask-study-002

本篇主要记录和实践flask模块中的render_template,url_for,redirect函数。这三个函数都用于返回给客户端。

1. render_template使用

通过render_template函数进行模板的渲染

app.py同级目录下,创建templates目录,用于存放需要flask渲染的模板

from flask import Flask, render_template

app = Flask(__name__)
app.config['DEBUG'] = True

@app.route('/')
def index():
    #return "hello,world"
    return render_template('index.html')

@app.route('/user/<name>')
def user(name):
    return f"hello,{name}"

if __name__ == "__main__":
    app.run()

templates/index.html内容:

<h1>
hello,world
</h1>

访问:http://127.0.0.1:5000/ 获取到模板index.html的内容

2. redirect使用

通过redirect函数进行重定向

from flask import Flask, render_template, redirect

app = Flask(__name__)
app.config['DEBUG'] = True

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/index')
def newindex():
    return redirect('/')

@app.route('/user/<name>')
def user(name):
    return f"hello,{name}"

if __name__ == "__main__":
        app.run()

3. url_for使用

url_for一般使用在2个场景中。redirect函数参数为(location,code,response),url_for函数就是来代替location的

  • 在视图函数中,通过url_for指定url的别名
  • 在模板中,通过url_for来加载静态资源,以及替代action的url
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章