Skip to content

Instantly share code, notes, and snippets.

@wcp1231
Last active December 24, 2015 04:19
Show Gist options
  • Save wcp1231/6742682 to your computer and use it in GitHub Desktop.
Save wcp1231/6742682 to your computer and use it in GitHub Desktop.
修改静态文件地址版本号的python脚本,给HTML里的css、js、图片等加上版本,使得静态资源既能缓存也能实时更新
# -*- coding: utf-8 -*-
import sys
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime
import os
import re
def build_replace_func():
version_string = "?ver=%s" % datetime.now().strftime("%Y%m%d%H")
def func(match_obj):
return match_obj.group('prefix') + version_string
return func
SRC_PATTERN = re.compile(r'(?P<prefix><(script|link|img)[^@%>]*=["|\'][^"\']*\.(js|css|png|jpg))(\?ver=\d+)?')
REPLACE_FUNC = build_replace_func()
def scan_jsp_files(project_dir):
jsp_files = []
os.chdir(project_dir)
for root, dirs, files in os.walk('./'):
for file in files:
if file.endswith('.jsp'):
jsp_files.append(os.path.join(root, file))
return jsp_files
def replace_js_css_png_jpg_version(content):
return re.sub(SRC_PATTERN, REPLACE_FUNC, content)
def parse_and_replace_version(file):
reader = open(file, 'r', encoding="utf-8")
content = reader.read()
content = replace_js_css_png_jpg_version(content)
return content
def update_static_file_version(file):
content = parse_and_replace_version(file)
if content:
writer = open(file, 'w', encoding="utf-8")
writer.write(content)
writer.close()
#print("Updated " + file)
def update_project_static_file_version(project_dir):
jsp_files = scan_jsp_files(project_dir)
with ThreadPoolExecutor(max_workers=4) as executor:
for file in jsp_files:
executor.submit(update_static_file_version, file)
if __name__ == "__main__":
if len(sys.argv) > 1:
project_dir = sys.argv[1]
else:
project_dir = input("Project Dir?\n")
begin_time = datetime.now()
update_project_static_file_version(project_dir)
print(datetime.now() - begin_time)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment