reorx
8/15/2017 - 9:25 AM

Call django collectstatic without involving the whole project, inspired by https://github.com/syntarsus/minimal-django

Call django collectstatic without involving the whole project, inspired by https://github.com/syntarsus/minimal-django

# coding: utf-8
# This is the original implementation before I got inspiration from minimal-django

import os
import sys
import string
import random
import importlib
from django.core.management import execute_from_command_line


settings_template = """# coding: utf-8

SECRET_KEY = 'A-random-secret-key!'

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.contenttypes',
    'django.contrib.staticfiles',
]

STATIC_URL = '{static_url}'
STATIC_ROOT = '{static_root}'
"""


if __name__ == '__main__':
    django_settings_module = sys.argv[1]

    settings = importlib.import_module(django_settings_module)

    pure_settings = settings_template.format(
        static_url=settings.STATIC_URL,
        static_root=settings.STATIC_ROOT,
    )

    rand_str = ''.join(random.choice(string.ascii_lowercase) for i in xrange(5))
    prefix = 'django_settings_{}'.format(rand_str)
    filename = prefix + '.py'

    with open(filename, 'w') as f:
        f.write(pure_settings)

    print 'write to tempfile: {}'.format(filename)

    os.environ.setdefault('DJANGO_SETTINGS_MODULE', prefix)
    execute_from_command_line(['manage.py', 'collectstatic', '--no-input', '-c'])

    os.unlink(filename)
# coding: utf-8
# Usage: python django_static_collector.py myapp.settings

import sys
import importlib

from django.conf import settings
from django.core.management import execute_from_command_line


def main():
    app_settings_module = sys.argv[1]
    app_settings = importlib.import_module(app_settings_module)

    settings.configure(
        DEBUG=True,
        SECRET_KEY='A-random-secret-key!',
        INSTALLED_APPS=[
            'django.contrib.admin',
            'django.contrib.contenttypes',
            'django.contrib.staticfiles',
        ],
        STATIC_URL=app_settings.STATIC_URL,
        STATIC_ROOT=app_settings.STATIC_ROOT,
    )

    execute_from_command_line(['manage.py', 'collectstatic', '--no-input', '-c'])


if __name__ == '__main__':
    main()