Created
November 12, 2013 12:24
-
-
Save zhwei/7429973 to your computer and use it in GitHub Desktop.
cache htmls in memory
静态网站加速 Python & bottle
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
# import os | |
import md5 | |
import bottle | |
#HTML = "output" | |
HTML = "/home/zhwei/blog" | |
global status | |
status = 0 | |
bucket = dict() | |
def get_real_path(path): | |
""" Get file abs path """ | |
return HTML + path | |
def get_content(path): | |
"""just read file""" | |
with open(get_real_path(path)) as fi: | |
return fi.read() | |
def get_path_md5(path): | |
"""Get file md5""" | |
_key = md5.new() | |
_key.update(get_content(path)) | |
return _key.hexdigest() | |
def get_set(path): | |
""" | |
if url in dict return it | |
else catch or 404 | |
""" | |
if bucket.has_key(path): | |
return bucket[path][0] | |
else: | |
try: | |
content=get_content(path) | |
except IOError: | |
bottle.abort(404) | |
bucket[path]=(content, get_path_md5(path)) | |
return content | |
def check(): | |
"""check htmls md5""" | |
for path in bucket: | |
if bucket[path][1] != get_path_md5(path): | |
try: | |
bucket[path]=(get_content(path), get_path_md5(path)) | |
except IOError: | |
pass | |
@bottle.hook('after_request') | |
def after(): | |
""" | |
every 7 request | |
check once | |
""" | |
global status | |
status += 1 | |
if status >= 7: | |
check() | |
status = 0 | |
@bottle.route('<path:re:.*\.html|\/>') | |
def cache(path): | |
"""htmls""" | |
if path=='/':path='/index.html' | |
return get_set(path) | |
@bottle.error(404) | |
@bottle.error(500) | |
def cache_error(error): | |
return "Error! <a href='/'>INDEX</a>" | |
@bottle.route('<filename:path>') | |
def send_static(filename): | |
"""other static files""" | |
return bottle.static_file(filename, root=HTML) | |
if '__main__' == __name__: | |
# bottle.run(host='0.0.0.0', port=1267, debug=True) | |
bottle.run(host='0.0.0.0', port=1267) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment