mirror of
https://github.com/jazzband/django-dbtemplates.git
synced 2026-03-16 22:20:28 +00:00
new management command 'sync_templates' for syncing the templates bidirectional
git-svn-id: https://django-dbtemplates.googlecode.com/svn/trunk@27 cfb8ba98-e953-0410-9cff-959ffddf5974 committer: leidel <leidel@cfb8ba98-e953-0410-9cff-959ffddf5974> --HG-- extra : convert_revision : 252aa837acd100f5a4588f12d7ea33c5adf30b3c
This commit is contained in:
parent
1738279bc4
commit
a9df6d73b1
7 changed files with 114 additions and 132 deletions
2
LICENSE
2
LICENSE
|
|
@ -1,4 +1,4 @@
|
|||
Copyright (c) 2007, Jannis Leidel
|
||||
Copyright (c) 2007-2008, Jannis Leidel
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
|
|
|
|||
0
dbtemplates/management/commands/__init__.py
Normal file
0
dbtemplates/management/commands/__init__.py
Normal file
80
dbtemplates/management/commands/sync_templates.py
Normal file
80
dbtemplates/management/commands/sync_templates.py
Normal file
|
|
@ -0,0 +1,80 @@
|
|||
import os
|
||||
import re
|
||||
from optparse import make_option
|
||||
|
||||
from django.conf import settings
|
||||
from django.contrib.sites.models import Site
|
||||
from django.core.management.base import CommandError, NoArgsCommand
|
||||
from django.template.loaders.app_directories import app_template_dirs
|
||||
|
||||
from dbtemplates.models import Template
|
||||
|
||||
class Command(NoArgsCommand):
|
||||
help = "Syncs file system templates with the database bidirectionally."
|
||||
option_list = NoArgsCommand.option_list + (
|
||||
make_option("-e", "--ext", dest="ext", action="store", default="html",
|
||||
help="extension of the files you want to sync with the database "
|
||||
"[default: %default]"),
|
||||
make_option("-f", "--force", action="store_true", dest="force",
|
||||
default=False, help="overwrite existing database templates")
|
||||
)
|
||||
def handle_noargs(self, **options):
|
||||
extension = options.get('ext')
|
||||
force = options.get('force')
|
||||
|
||||
if not extension.startswith("."):
|
||||
extension = ".%s" % extension
|
||||
|
||||
try:
|
||||
site = Site.objects.get_current()
|
||||
except:
|
||||
site = None
|
||||
|
||||
if site is None:
|
||||
raise CommandError("Please make sure to have the sites contrib "
|
||||
"app installed and setup with a site object")
|
||||
|
||||
if not type(settings.TEMPLATE_DIRS) in (tuple, list):
|
||||
raise CommandError("Please make sure settings.TEMPLATE_DIRS is a "
|
||||
"list or tuple.")
|
||||
|
||||
templatedirs = [d for d in
|
||||
settings.TEMPLATE_DIRS + app_template_dirs if os.path.isdir(d)]
|
||||
|
||||
for templatedir in templatedirs:
|
||||
for dirpath, subdirs, filenames in os.walk(templatedir):
|
||||
for f in [f for f in filenames if f.endswith(extension)
|
||||
and not f.startswith(".")]:
|
||||
path = os.path.join(dirpath, f)
|
||||
name = path.split(templatedir)[1][1:]
|
||||
try:
|
||||
t = Template.objects.get(name__exact=name)
|
||||
except Template.DoesNotExist:
|
||||
confirm = raw_input(
|
||||
"\nA '%s' template doesn't exist in the database.\n"
|
||||
"Create it with '%s'?"
|
||||
" (y/n): """ % (name, path))
|
||||
if confirm.lower().startswith('y'):
|
||||
t = Template(name=name,
|
||||
content=open(path, "r").read())
|
||||
t.save()
|
||||
t.sites.add(site)
|
||||
else:
|
||||
while 1:
|
||||
confirm = raw_input(
|
||||
"\n%s exists in the database.\n"
|
||||
"(1) Overwrite %s with '%s'\n"
|
||||
"(2) Overwrite '%s' with %s\n"
|
||||
"Type 1 or 2 or press <Enter> to skip: "
|
||||
% (t.__repr__(),
|
||||
t.__repr__(), path,
|
||||
path, t.__repr__()))
|
||||
if confirm == '' or confirm in ('1', '2'):
|
||||
if confirm == '1':
|
||||
t.content = open(path, 'r').read()
|
||||
t.save()
|
||||
t.sites.add(site)
|
||||
elif confirm == '2':
|
||||
_f = open(path, 'w').write(t.content)
|
||||
_f.close()
|
||||
break
|
||||
|
|
@ -64,4 +64,4 @@ __test__ = {'API_TESTS':"""
|
|||
'<html><head></head><body>Welcome at MainPage</body></html>'
|
||||
>>> loader.get_template("sub.html").render(Context({'title':'SubPage'}))
|
||||
'<html><head></head><body>This is SubPage</body></html>'
|
||||
"""}
|
||||
"""}
|
||||
|
|
|
|||
|
|
@ -1,118 +1,17 @@
|
|||
#!/usr/bin/env python
|
||||
import os
|
||||
import sys
|
||||
"""This is just for backwards compatiblity"""
|
||||
from optparse import OptionParser
|
||||
from django.core.management import call_command
|
||||
|
||||
def setup_environ():
|
||||
"""
|
||||
Configure the runtime environment.
|
||||
"""
|
||||
project_directory = os.getcwd()
|
||||
project_name = os.path.basename(project_directory)
|
||||
sys.path.append(os.path.join(project_directory, '..'))
|
||||
project_module = __import__(project_name, {}, {}, [''])
|
||||
sys.path.pop()
|
||||
def main():
|
||||
parser = OptionParser()
|
||||
parser.add_option("-e", "--ext", dest="ext", action="store", type="string",
|
||||
help="file extension of the files you want to sync [default: %default]",
|
||||
default="html")
|
||||
parser.add_option("-f", "--force", action="store_true", dest="force",
|
||||
default=False, help="overwrite existing database templates")
|
||||
opts, args = parser.parse_args()
|
||||
|
||||
# Set DJANGO_SETTINGS_MODULE appropriately.
|
||||
os.environ['DJANGO_SETTINGS_MODULE'] = '%s.settings' % project_name
|
||||
return project_name, project_module
|
||||
|
||||
def synctemplates(project_module, extension, overwrite):
|
||||
"""
|
||||
Helper function for syncing templates in TEMPLATES_DIRS with the
|
||||
dbtemplates contrib app.
|
||||
"""
|
||||
from django.contrib.sites.models import Site
|
||||
from django.template import TemplateDoesNotExist
|
||||
from dbtemplates.models import Template
|
||||
|
||||
if not extension.startswith("."):
|
||||
extension = ".%s" % extension
|
||||
|
||||
tried = []
|
||||
synced = []
|
||||
existing = []
|
||||
overwritten = []
|
||||
|
||||
try:
|
||||
site = Site.objects.get_current()
|
||||
except:
|
||||
site = None
|
||||
|
||||
if site is not None:
|
||||
if type(project_module.settings.TEMPLATE_DIRS) in (tuple, list):
|
||||
for template_dir in project_module.settings.TEMPLATE_DIRS:
|
||||
if os.path.isdir(template_dir):
|
||||
for dirpath, subdirs, filenames in os.walk(template_dir):
|
||||
for file in filenames:
|
||||
if file.endswith(extension) and not file.startswith("."):
|
||||
filepath = os.path.join(dirpath, file)
|
||||
filename = filepath.split(template_dir)[1][1:]
|
||||
try:
|
||||
try:
|
||||
t = Template.objects.get(name__exact=filename)
|
||||
except Template.DoesNotExist:
|
||||
filecontent = open(filepath, "r").read()
|
||||
t = Template(name=filename, content=filecontent)
|
||||
t.save()
|
||||
t.sites.add(site)
|
||||
synced.append(filename)
|
||||
else:
|
||||
if overwrite:
|
||||
t.content = open(filepath, "r").read()
|
||||
t.save()
|
||||
t.sites.add(site)
|
||||
overwritten.append(t.name)
|
||||
else:
|
||||
existing.append(t.name)
|
||||
except IOError:
|
||||
tried.append(filepath)
|
||||
except:
|
||||
raise TemplateDoesNotExist
|
||||
|
||||
if len(existing) > 0:
|
||||
print "Already existing templates (use --force to overwrite):"
|
||||
for e in existing:
|
||||
print e
|
||||
|
||||
if len(overwritten) > 0:
|
||||
print "Overwritten existing templates:"
|
||||
for o in overwritten:
|
||||
print o
|
||||
|
||||
if len(synced) > 0:
|
||||
print "Successfully synced templates:"
|
||||
for s in synced:
|
||||
print s
|
||||
|
||||
if len(tried) > 0:
|
||||
print "Tried to sync but failed:"
|
||||
for t in tried:
|
||||
print t
|
||||
else:
|
||||
print "Please make sure settings.TEMPLATE_DIRS is a list or tuple."
|
||||
|
||||
def main((options, args)):
|
||||
try:
|
||||
project_name, project_module = setup_environ()
|
||||
print "Loading settings from project '%s'.. done." % project_name
|
||||
synctemplates(project_module, options.ext, options.overwrite)
|
||||
except ImportError, e:
|
||||
print "Please make sure a settings.py file exists in the current directory."
|
||||
print e
|
||||
sys.exit(0)
|
||||
except OSError, e:
|
||||
print e
|
||||
sys.exit(0)
|
||||
except:
|
||||
sys.exit(0)
|
||||
call_command('sync_templates', **{'ext': opts.ext, 'force': opts.force})
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = OptionParser()
|
||||
parser.add_option("-e", "--ext", dest="ext", action="store",
|
||||
help="file extension of the files you want to sync with the database [default: %default]",
|
||||
type="string", default="html")
|
||||
parser.add_option("-f", "--force",
|
||||
action="store_true", dest="overwrite", default=False,
|
||||
help="overwrite existing database templates")
|
||||
main(parser.parse_args())
|
||||
main()
|
||||
|
|
|
|||
37
setup.py
37
setup.py
|
|
@ -1,19 +1,22 @@
|
|||
from distutils.core import setup
|
||||
|
||||
setup(name='dbtemplates',
|
||||
version='0.2.5',
|
||||
description='Template loader for database stored templates',
|
||||
author='Jannis Leidel',
|
||||
author_email='jannis@leidel.info',
|
||||
url='http://code.google.com/p/django-databasetemplateloader/',
|
||||
scripts=['dbtemplates/sync_templates.py',],
|
||||
packages=['dbtemplates'],
|
||||
package_dir={ 'dbtemplates': 'dbtemplates' },
|
||||
classifiers=['Development Status :: 4 - Beta',
|
||||
'Environment :: Web Environment',
|
||||
'Intended Audience :: Developers',
|
||||
'License :: OSI Approved :: BSD License',
|
||||
'Operating System :: OS Independent',
|
||||
'Programming Language :: Python',
|
||||
'Topic :: Utilities'],
|
||||
)
|
||||
setup(
|
||||
name='dbtemplates',
|
||||
version='0.3.0',
|
||||
description='Template loader for database stored templates',
|
||||
author='Jannis Leidel',
|
||||
author_email='jannis@leidel.info',
|
||||
url='http://code.google.com/p/django-databasetemplateloader/',
|
||||
scripts=['dbtemplates/sync_templates.py',],
|
||||
packages=['dbtemplates'],
|
||||
package_dir={'dbtemplates': 'dbtemplates'},
|
||||
classifiers=[
|
||||
'Development Status :: 4 - Beta',
|
||||
'Environment :: Web Environment',
|
||||
'Intended Audience :: Developers',
|
||||
'License :: OSI Approved :: BSD License',
|
||||
'Operating System :: OS Independent',
|
||||
'Programming Language :: Python',
|
||||
'Topic :: Utilities'
|
||||
]
|
||||
)
|
||||
|
|
|
|||
Loading…
Reference in a new issue