Skip to content

Instantly share code, notes, and snippets.

@vemacs
Last active August 29, 2015 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vemacs/30234df73b41be7a2b3c to your computer and use it in GitHub Desktop.
Save vemacs/30234df73b41be7a2b3c to your computer and use it in GitHub Desktop.
import datetime
import threading
from flask import Flask
from collections import OrderedDict
import json
import hashlib
import os
import markdown
class Entry():
def __init__(self, entry_file):
self.entry_file = entry_file
def get_title(self):
return os.path.splitext(os.path.basename(self.entry_file))[0].replace("_", " ")
def get_hash(self):
return str(hashlib.md5(self.get_title()).hexdigest())
def get_modified(self):
return float(os.path.getmtime(self.entry_file))
def get_created(self):
file_ctime = os.path.getctime(self.entry_file)
return float(Blog.create_cache.get(self.get_hash(), str(file_ctime)))
def get_contents(self):
with open(self.entry_file, "r") as actual_file:
return markdown.markdown(actual_file.read())
def pretty_time(self, utime):
return datetime.datetime.fromtimestamp(utime).strftime('%Y-%m-%d %H:%M:%S')
class Blog:
create_cache = {} # workaround for ctime on *nix systems
entries = []
def __init__(self, app_path):
self.app_path = app_path
with open(os.path.join(app_path, "entries", "create_cache.json")) as cache_file:
self.create_cache = json.loads(cache_file.read())
self.update_entries()
def update_entries(self):
entry_dir = os.path.join(self.app_path, "entries")
for entry_file in os.listdir(entry_dir):
if entry_file.endswith(".md"):
self.entries.append(Entry(os.path.join(entry_dir, entry_file)))
time_dict = {}
temp_cache = {}
for entry in self.entries:
time_dict[entry.get_created()] = entry
temp_cache[entry.get_hash()] = entry.get_created()
self.create_cache = temp_cache
self.entries = self.sort_dict_by_key(time_dict).values()
with open(os.path.join(self.app_path, "entries", "create_cache.json"), "w") as cache_file:
cache_file.write(json.dumps(self.create_cache))
def sort_dict_by_key(self, to_sort):
return OrderedDict(reversed(sorted(to_sort.items(), key=lambda t: t[0])))
app = Flask(__name__)
blog = Blog(app.root_path)
def schedule_update():
threading.Timer(5, schedule_update).start()
blog.update_entries()
@app.route("/")
def show_entries():
lole = ""
for entry in blog.entries:
entry_html = ""
try:
entry_html += "<h1>" + entry.get_title() + "</h1>"
create = entry.get_created()
modify = entry.get_modified()
entry_html += "<h3> Created: " + entry.pretty_time(create) + "</h3>"
if (modify - create) >= 300.0: # support for ninja edits
entry_html += "<h3> Modified: " + entry.pretty_time(modify) + "</h3>"
entry_html += entry.get_contents()
except:
entry_html = ""
lole += entry_html
return lole
if __name__ == "__main__":
schedule_update()
app.run(debug=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment