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')
相关推荐
wangsir.4 小时前
测试之自动化测试常用函数
python·测试
铁蛋AI编程实战4 小时前
MemoryLake 实战:构建超长对话 AI 助手的完整代码教程
人工智能·python·microsoft·机器学习
清水白石0084 小时前
《为什么说 deque 是 Python 滑动窗口的“隐藏神器”?深入解析双端队列的高效之道》
开发语言·python
kjkdd4 小时前
5. LangChain设计理念和发展历程
python·语言模型·langchain·ai编程
摘星编程4 小时前
CANN ops-nn 激活函数算子全解析:从ReLU到GELU的演进与实现
python
love530love4 小时前
【高阶编译】Windows 环境下强制编译 Flash Attention:绕过 CUDA 版本不匹配高阶指南
人工智能·windows·python·flash_attn·flash-attn·flash-attention·定制编译
DeniuHe4 小时前
Pytorch中的众数
人工智能·pytorch·python
新缸中之脑4 小时前
开发AI代理必备的8个Python 库
开发语言·人工智能·python
WKP94184 小时前
照片生成心形工具【免费】【下载即可使用】
python
Java后端的Ai之路4 小时前
【Python 教程14】- 网络编程
网络·python·php