Skip to content

Instantly share code, notes, and snippets.

@jstacoder
Created January 14, 2015 04:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jstacoder/2754ed43b2b28ef799ef to your computer and use it in GitHub Desktop.
Save jstacoder/2754ed43b2b28ef799ef to your computer and use it in GitHub Desktop.
flask_script - gather_templates command (like djangos management command, but for flask)
from flask import Flask
from flask_script import Manager
from flask_admin import Admin
import os.path as op
import os
app = Flask(__name__)
manager = Manager(app)
admin = Admin(app) #<-- this gives our app some templates to gather
def gather_template_files(verbose=False):
template_files = map(lambda x: (
x[0],
x[1],
open(x[0],'r').read()
),map(lambda x: (
x.filename,
x.name
),map(
app.jinja_env.get_template,
app.jinja_env.list_templates()
)
)
)
base = 'templates'
success = True
for location,name,text in template_files:
filename = op.join(base,name)
filedir = op.join(base,op.dirname(name))
if not op.exists(filedir):
if verbose:
print 'Directory path {} does not exist, creating now...\n\n'.format(filedir)
os.makedirs(filedir)
with open(filename,'w') as f:
try:
if verbose:
print 'Preparing to write file {}\n'.format(filename)
f.write(text)
if verbose:
print 'wrote {} to file\n'.format(filename)
except:
success = False
pass
return success
@manager.command
def gather_templates():
if gather_template_files():
print 'all template files gathered'
else:
print 'error gathering templates'
@manager.command
def gather_templates_verbose():
if gather_template_files(verbose=True):
print 'all template files gathered'
else:
print 'error gathering templates'
if __name__ == "__main__":
manager.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment