像SpringBoot一样使用Flask - 2.静态资源访问及模版

一、安装并导入 render_template

功能:渲染/加载模板,一般是html页面

参数:函数的第一个参数是模板的文件名,必填,后面的参数都是键值对,表示模板中变量对应的值,非必填 (不填界面也不会展示成变量名,只是不填则不渲染)。

二、修改app主入口配置,类似SpringBoot的yaml配置。

python 复制代码
from flask import Flask, render_template

app = Flask(__name__,
            static_url_path='/',  # 配置静态文件的访问 url 前缀)
            static_folder='static',  # 配置静态文件的文件夹
            template_folder='templates'  # 配置模板文件的文件夹
            )

static_url_path和static_folder写上去,可以在引用css/js可以更好的用/代替写相对路径,不用看到../../类似的写法

三、测试

增加测试请求/index

python 复制代码
name = '小明'
year = '2024'


@app.route('/index')
def happy_new_year():
    return render_template('test/index.html', name=name, year=year)

controller

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title><title>{{ year }} 新年快乐</title>
</head>
<link rel="stylesheet" href="/test/index.css">
<body>
    <h2 id="indexId">你好 {{ name }} , 祝你 {{ year }} 平安喜乐,玩好Flask</h2>
</body>
</html>

index.html

css 复制代码
#indexId{
    color: aquamarine;
}

index.css

目录结构

四、运行

五、总结

这个很像springboot里面的Thymeleaf。重点在配置上,避免后续static路径,项目一增加,看着有点乱。建议写上去,少一点../../,增加代码可读性

相关推荐
Daydream.V11 分钟前
Python Flask超全入门实战教程|从零基础到项目部署
大数据·python·flask
databook36 分钟前
Manim物理模拟:别自己写欧拉了!
python·数学·动效
程序猿追1 小时前
我搭了个网页工具:输入关键词,SERP API 自动吐出比价 Excel
后端
Lee川1 小时前
RAG 实战:从一篇掘金文章出发,拆解检索增强生成的全链路
前端·人工智能·后端
Lee川1 小时前
MCP 高德地图实战:当 AI 学会使用工具,一个协议如何重塑大模型的行动边界
前端·人工智能·后端
楼田莉子1 小时前
C++17新特性:__had_include/属性/求值顺序规则
开发语言·c++·后端
程序员cxuan2 小时前
Codex 把我家烂网给优化后,我 TM 直接原地起飞了。
人工智能·后端·程序员
IT_陈寒2 小时前
Redis批量删除踩了坑,原来DEL命令不是万能的
前端·人工智能·后端
香蕉鼠片2 小时前
Python进阶学习
开发语言·python
叫我少年2 小时前
C# 命名空间与 using 指令 — 文件范围、全局导入、别名
后端