像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路径,项目一增加,看着有点乱。建议写上去,少一点../../,增加代码可读性

相关推荐
hu_yuchen1 分钟前
问卷系统自动化测试报告
软件测试·python
百锦再22 分钟前
第8章 模块系统
android·java·开发语言·python·ai·rust·go
IT_陈寒33 分钟前
7个鲜为人知的JavaScript性能优化技巧,让你的网页加载速度提升50%
前端·人工智能·后端
几颗流星34 分钟前
Rust 常用语法速记 - 迭代器
后端·rust
Ashlee_code35 分钟前
经纪柜台系统解析:从今日国际金融动荡看证券交易核心引擎的变革
python·架构·系统架构·区块链·vim·柜台·香港券商
清空mega1 小时前
从零开始搭建 flask 博客实验(4)
后端·python·flask
bcbnb1 小时前
iPhone HTTPS 抓包,从无法抓包到定位问题的流程(Charles/tcpdump/Wireshark/Sniffmaster)
后端
Data_Adventure1 小时前
TypeScript 开发者转向 Java:学习重点与思维迁移指南
后端
吴祖贤2 小时前
Spring AI 零基础入门:从踩坑到上手的完整指南
后端
code_std2 小时前
SpringBoot 登录验证码
java·spring boot·后端