本文共 1275 字,大约阅读时间需要 4 分钟。
这里举个例子:
通过Python管理静态资源。但有时候,js或者css更新了,浏览器不知道,还使用缓存的情况。
如下所示:
通过在url中带个?这种方式,使得浏览器去获取新的资源
看下根请求下相关链接:
后面这一串是根据时间产生的随机数。
如果是开发环境,我们通过这种方式,使得客户端浏览器都获取到新的资源。
生产环境,通过文件进行指定版本:
相关的python代码如下:
在配置文件夹中新增:
在静态资源管理文件中,local_setting.py中配置了这个文件,就读一行,也就是版本号,如果没有,就使用随机数据去做,相关代码如下:
UrlManager.py
from application import appfrom common.libs.DataHelper import getCurrentTimeimport osclass UrlManager(object): @staticmethod def buildUrl(path): config_domain = app.config['DOMAIN'] return "%s%s" % (config_domain['www'], path) @staticmethod def buildStaticUrl(path): path = "/static" + path + "?ver=" + UrlManager.getReleaseVersion(); return UrlManager.buildUrl(path) #版本管理 #开发模式 使用时间作为版本号 #生产模式 使用版本文件进行管理 @staticmethod def getReleaseVersion(): ver = "%s" % (getCurrentTime("%Y%m%d%H%M%S%f")) release_path = app.config.get("RELEASE_PATH"); if release_path and os.path.exists(release_path): with open(release_path, "r") as f: ver = f.readline() return ver return ver
其中getCurrentTimer如下:
DataHelper.py
import datetimedef getCurrentTime(frm = "%Y-%m-%d %H:%M:%S"): dt = datetime.datetime.now() return dt.strftime(frm)
app.config.get(XXX)中这个app是在核心文件(核心变量定义文件中定义的)
如下:
转载地址:http://bdmif.baihongyu.com/