Flask学习(二):flask模板渲染

Flask没有自己模板引擎,使用的是 jinja2 模板引擎,可以帮助我们将数据渲染到各种格式的文档中,如 HTML、XML、Markdown 等。

中文文档地址:Jinja2中文文档_w3cschool

程序示例:

python 复制代码
from flask import Flask, render_template,request,redirect
# template_folder= 可以指定模板渲染地址
app = Flask(__name__,template_folder=)
# 设置请求方法 默认为get方法
@app.route("/login", methods=['GET', 'POST'])
def login():
    #request可以获取相关请求数据
    if request.method == 'GET':
        return render_template("login.html")
    user = request.form.get("user")
    pwd = request.form.get("pwd")
    if "123" == user and "123" == pwd:
        # 进行重定向
        return redirect("/index")
    else:
        return render_template("login.html", msg = "请输入正确的用户名和密码")
# 重定向路由地址
@app.route("/index", methods=['GET'])
def index():
    return "欢迎登录后台管理系统!!"
​
if __name__ == "__main__":
    app.run()

模板渲染地址: 模板渲染地址默认是在templates文件夹下,也可以创建flask对象的时候指定:app = Flask(name,template_folder=)

python 复制代码
def __init__(
    self,
    import_name: str,
    static_url_path: str | None = None,
    static_folder: str | os.PathLike[str] | None = "static",
    static_host: str | None = None,
    host_matching: bool = False,
    subdomain_matching: bool = False,
    # 默认地址
    template_folder: str | os.PathLike[str] | None = "templates",
    instance_path: str | None = None,
    instance_relative_config: bool = False,
    root_path: str | None = None,
):

请求响应输出:

复制代码
    
python 复制代码
    request.method  提交的方法
    request.args  get请求提及的数据
    request.form   post请求提交的数据
    request.values  post和get提交的数据总和
    request.cookies  客户端所带的cookie
    request.headers  请求头
    request.path     不带域名,请求路径
    request.full_path  不带域名,带参数的请求路径
    request.script_root
    request.url           带域名带参数的请求路径
    request.base_url      带域名请求路径
    request.url_root      域名
    request.host_url      域名
    request.host          127.0.0.1:500
    request.files
​
    # 响应相关信息
    return "字符串"
    return render_template('html模板路径',**{})
    # 重定向
    return redirect('/index.html')
相关推荐
兵慌码乱7 小时前
基于 MediaPipe 与 PySide2 的手势交互音乐控制系统实现:轻量化视觉交互全流程解析
python·opencv·计算机视觉·人机交互·手势识别·mediapipe·pyside2
luckdewei10 小时前
FastAPI 资产管理系统实战:复杂 ORM 关联、Alembic 迁移与 N+1 查询优化
python
aqi0016 小时前
15天学会AI应用开发(八)使用向量数据库实现RAG功能
人工智能·python·大模型·ai编程·ai应用
Csvn17 小时前
`functools.lru_cache` —— 一行代码搞定缓存加速
后端·python
金銀銅鐵1 天前
[Python] 从《千字文》中随机挑选汉字
后端·python
cup112 天前
[技术复盘] Windows Python 打包实战:Nuitka 环境踩坑总结与 CI 自动化构建全指南
python·ai·环境变量·ci·nuitka·skill
aqi002 天前
15天学会AI应用开发(七)有了大模型为什么还要引入RAG
人工智能·python·大模型·ai编程·ai应用
金銀銅鐵2 天前
用 Python 实现 Take-Away 游戏
python·游戏