老鬼的博客 来都来啦,那就随便看看吧~
html全局替换时间戳预防缓存
发布于: 2025-01-14 更新于: 2025-01-14 分类于:  阅读次数: 

一:背景

1
2
3
目前很多前端的资源是放在OSS上并且加了CDN的缓存,为了避免前端调整后发布OSS
不生效,所以一般在发布的时候统一替换html引入的资源路径,如果JS中也引入了
一些路径,则需要手动调整路径

二:代码

2.1 环境

1
需要安装python3,并且此指令是放在当前路径执行的,如更改路径请自行调整。

2.2 v.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import os;
import re;
import time
from datetime import datetime;
from urllib.parse import urlparse, urlunparse, parse_qs, urlencode

# 获取某个目录下的所有的js和html文件,并读取内容
def fileList(directory):
filesInfo = []
for root, dirs, files in os.walk(directory):
for file in files:
# if file.endswith('.html') or file.endswith('.js'):
if file.endswith('.html') :
filePath = os.path.join(root, file)
filesInfo.append({'name': file, 'path': filePath})
return filesInfo

# 替换时间戳
def replaceTimestamp(filePath):
print(filePath)
replaceSuffix(filePath,".js");
# replaceSuffix(filePath,".css");

# 替换后缀
def replaceSuffix(filePath, suffix):
with open(filePath, 'r', encoding='utf-8') as file:
fileContent = file.read();
content = add_timestamp_to_assets(fileContent);
with open(filePath, 'w+', encoding='utf-8') as file:
file.write(content);

def add_or_update_timestamp(url):
# 解析 URL
parsed_url = urlparse(url)

# 解析查询参数
query_params = parse_qs(parsed_url.query)

# 检查是否已经有时间戳参数
if 't' in query_params:
# 替换旧的时间戳
query_params['v'] = [loadTimestamp()]
else:
# 添加新的时间戳参数
query_params['v'] = [loadTimestamp()]

# 重新编码查询参数
new_query = urlencode(query_params, doseq=True)

# 构造新的 URL
new_parsed_url = parsed_url._replace(query=new_query)
new_url = urlunparse(new_parsed_url)

return new_url

def add_timestamp_to_assets(html_content):

# 定义正则表达式模式来匹配 CSS 和 JS 文件的引用
css_js_pattern = re.compile(r'(<(link|script)[^>]*\b(?:href|src)=["\'])([^"\']+)(["\'][^>]*>)', re.IGNORECASE)

# 使用 sub() 方法替换匹配到的内容,增加或更新时间戳
def update_asset_url(match):
prefix = match.group(1) # <link ...src=" 或 <script ...src="
url = match.group(3) # CSS 或 JS 文件的 URL
suffix = match.group(4) # " ...> 或 ' ...>

# 更新 URL 中的时间戳
updated_url = add_or_update_timestamp(url)

return prefix + updated_url + suffix

# 执行替换
updated_html_content = css_js_pattern.sub(update_asset_url, html_content)

return updated_html_content

def loadTimestamp():
# 获取当前时间戳
timestamp = time.time()
# 将时间戳转换为 datetime 对象
dt_object = datetime.fromtimestamp(timestamp)
# 将 datetime 对象格式化为字符串
formatted_time = dt_object.strftime("%Y%m%d%H%M%S")
return formatted_time;
# 示例使用
dirPath = 'C:/Users/Administrator/Desktop/test'
dirPath = './';
files = fileList(dirPath)
for info in files:
replaceTimestamp(info['path']);
# print(f"File Name: {info['name']}, Path: {info['path']}")

2.3 v.bat

1
2
python v.py
pause

1.jpg

1.jpg

*************感谢您的阅读*************