Skip to content

Instantly share code, notes, and snippets.

@roadsideseb
Created June 25, 2014 03:04
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 roadsideseb/e9661f8d117b02b4e39a to your computer and use it in GitHub Desktop.
Save roadsideseb/e9661f8d117b02b4e39a to your computer and use it in GitHub Desktop.
A quick and dirty way to add backward-compatible app config to Django app (for Django 1.7 support)
# -*- coding: utf-8 -*-
#! /usr/bin/env python
import os
import sys
import click
DEFAULT_CONFIG_TEMPLATE = "default_app_config = '{module_path}.{config_module}.{app_name}AppConfig'" # noqa
APPCONFIG_TEMPLATE = """# -*- coding: utf-8 -*-
from django.apps import AppConfig
class {app_name}AppConfig(AppConfig):
name = '{module_path}'
verbose_name = '{app_verbose_name}'
"""
@click.command()
@click.option('--project-dir')
@click.option('--module-name', default='apps')
@click.option('--dry-run', is_flag=True)
@click.option('--force', is_flag=True)
@click.argument('apps', nargs=-1)
def create_app_config(project_dir, module_name, dry_run, force, apps):
print "APPS", apps
for app_module in apps:
if '.' in app_module:
__, app_label = app_module.rsplit('.', 1)
app_dir = app_module.replace('.', '/')
else:
app_label = app_dir = app_module
if project_dir:
app_dir = os.path.join(project_dir, app_dir)
if not os.path.exists(app_dir):
print "ERROR: app directory doesn't exist"
sys.exit(2)
app_config = os.path.join(app_dir, "{}.py".format(module_name))
name_segments = map(lambda a: a.capitalize(), app_label.split('_'))
app_name = ''.join(name_segments)
app_verbose_name = ' '.join(name_segments)
app_config_content = APPCONFIG_TEMPLATE.format(
app_name=app_name, module_path=app_module,
app_verbose_name=app_verbose_name)
if dry_run:
print "=" * len(app_module)
print app_module
print "=" * len(app_module)
print
print "APP DIR:", app_dir
print "APP LABEL:", app_label
print
print app_config_content
print
continue
if not os.path.exists(app_config) or force:
print "Adding app config:", app_config
with open(app_config, 'w') as app_file:
app_file.write(app_config_content)
init_path = os.path.join(app_dir, '__init__.py')
default_config_set = False
is_empty = True
if os.path.exists(init_path):
with open(init_path) as init_file:
for number, line in enumerate(init_file):
if 'default_app_config' in line:
default_config_set = True
break
is_empty = number < 1
if not default_config_set:
print "Adding default config to", init_path
with open(init_path, 'a') as init_file:
if not is_empty:
init_file.write('\n\n')
init_file.write(DEFAULT_CONFIG_TEMPLATE.format(
module_path=app_module, app_name=app_name,
config_module=module_name))
if __name__ == '__main__':
create_app_config()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment