flask-study-002

liwl / 2024-01-16 / 原文

本篇主要记录flask的模板使用

1. 模板基本使用

通过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函数进行重定向

from flask import Flask, render_template, redirect

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

@app.route('/')
def index():
    #return "hello,world"
    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()