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')
相关推荐
hhzz5 小时前
基于监控视频的水位尺自动识别技术方案与实现
python·opencv·yolo·图像识别·cv
yongche_shi6 小时前
ragas官方文档中文版(五十)
开发语言·python·ai·ragas·如何评估和改进 rag 应用
weixin_408099676 小时前
OCR批量识别图片方案:从手动处理到自动化API系统(Python/Java/PHP实战)
图像处理·python·ocr·文字识别·api调用·批量识别·石榴智能
AI行业学习7 小时前
Notepad++ 官方下载 + 完整安装 + 全套优化配置(2026最新)
开发语言·人工智能·python·前端框架·html·notepad++
大圣编程8 小时前
Python中continue语句的用法是什么?
开发语言·前端·python
云烟成雨TD8 小时前
LangFlow 1.x 系列【5】可视化编辑页面功能说明
人工智能·python·agent
geovindu9 小时前
python: Functional Options Pattern
开发语言·后端·python·设计模式·惯用法模式·函数式选项模式
tryCbest10 小时前
Python 文件操作
服务器·python
涛声依旧-底层原理研究所10 小时前
Agent 长任务可靠性设计:实现暂停、恢复、续跑与崩溃重启的完整方案
人工智能·python·系统架构
AC赳赳老秦10 小时前
防火墙规则批量配置实战:OpenClaw 自动生成模板、批量下发与合规性校验全解析
java·开发语言·人工智能·python·github·php·openclaw