Skip to content
Snippets Groups Projects
Code owners
Assign users and groups as approvers for specific file changes. Learn more.
manage.py 2.20 KiB
#!/usr/bin/env python3
import os
import sys
import signal
import importlib
import argparse

def subscribe_to_signals():
    # raise SignalException when a signal is caught so django will exit gracefully
    class SignalException(Exception):
        pass

    def signal_handler(_s, _f):
        raise SignalException("signal %s received..." % (_s,))

    for s in [signal.SIGHUP, signal.SIGINT]:
        signal.signal(s, signal_handler)


def main(settings_module="tmss.settings"):
    # we typically use manage.py to manage the source (not the product) so this should typically point to the settings
    # module relative to this script in the src tree. But we allow overriding it for tmss_manage_django.

    parser = argparse.ArgumentParser()
    parser.add_argument("-C", action="store", dest="dbcredentials",
                        help="use database specified in this credentials file")
    parser.add_argument("-L", action="store", dest="ldapcredentials",
                        help="use LDAP service specified in this credentials file")
    args, unknownargs = parser.parse_known_args()
    if args.dbcredentials:
        os.environ["TMSS_DBCREDENTIALS"] = args.dbcredentials
    if args.ldapcredentials:
        os.environ["TMSS_LDAPCREDENTIALS"] = args.ldapcredentials

    # do subscribe to more signals than django does for proper exits during testing
    if os.environ.get('TMSS_RAISE_ON_SIGNALS', "False").lower() in ["true", "1", "on"]:
        subscribe_to_signals()

    # normal django startup. Specify the DJANGO_SETTINGS_MODULE, and run it.

    os.environ.setdefault("DJANGO_SETTINGS_MODULE", settings_module)
    spec = importlib.util.find_spec(os.environ['DJANGO_SETTINGS_MODULE'])
    settings_path = spec.origin

    print("Using settings module %s" % settings_path)

    try:
        from django.core.management import execute_from_command_line
    except ImportError as exc:
        raise ImportError(
            "Couldn't import Django. Are you sure it's installed and "
            "available on your PYTHONPATH environment variable? Did you "
            "forget to activate a virtual environment?"
        ) from exc

    execute_from_command_line([sys.argv[0]] + unknownargs)

if __name__ == "__main__":
    main()