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')
相关推荐
狐凄1 小时前
Python实例题:基于边缘计算的智能物联网系统
python·物联网·边缘计算
@十八子德月生1 小时前
第十章——8天Python从入门到精通【itheima】-99~101-Python基础综合案例-数据可视化(案例介绍=JSON格式+pyecharts简介)
大数据·python·信息可视化·pycharm·echarts·数据可视化
W说编程1 小时前
算法导论第二十四章 深度学习前沿:从序列建模到创造式AI
c语言·人工智能·python·深度学习·算法·性能优化
动能小子ohhh2 小时前
html实现登录与注册功能案例(不写死且只使用js)
开发语言·前端·javascript·python·html
Blue桃之夭夭3 小时前
Python爬虫(六):Scrapy框架
爬虫·python·scrapy
大模型铲屎官3 小时前
【深度学习-Day 31】CNN基石:彻底搞懂卷积层 (Convolutional Layer) 的工作原理
人工智能·pytorch·python·深度学习·机器学习·cnn·llm
struggle20253 小时前
DeepForest开源程序是用于 Airborne RGB 机器学习的 Python 软件包
开发语言·python
杜大哥3 小时前
Python:.py文件如何变成双击可执行的windows程序?(版本1)
开发语言·windows·python
四川兔兔4 小时前
Pytorch 实战四 VGG 网络训练
人工智能·pytorch·python·深度学习·机器学习·回归·vgg网络
猫头虎4 小时前
2025最新Python 100个常用函数在线体验项目
android·java·python·pycharm·django·pandas·pip