django.get_version

Here are the examples of the python api django.get_version taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

105 Examples 7

Example 1

Project: django-yubin Source File: base.py
def rfc_6532_support():
    """
    RFC 6532 is not properly supported in Django < 1.10 with Python 3.
    """
    django_version = django.get_version()
    return (six.PY2 or
            six.PY3 and StrictVersion(django_version) >= StrictVersion("1.10"))

Example 2

Project: djangocms-helper Source File: test_commands.py
    @unittest.skipIf(LooseVersion(django.get_version()) < LooseVersion('1.7'),
                     reason='check command available in Django 1.7+ only')
    def test_any_command_check(self):
        with work_in(self.basedir):
            with captured_output() as (out, err):
                args = copy(DEFAULT_ARGS)
                args['<command>'] = 'check'
                args['options'] = ['helper', 'check', '--extra-settings=cms_helper_extra.py']
                core(args, self.application)
        if DJANGO_1_7:
            # Django 1.7 complains about the test runner ... go figure ...
            self.assertTrue('1 issue' in err.getvalue())
        else:
            self.assertTrue('no issues' in out.getvalue())

Example 3

Project: django-development-fabfile Source File: local.py
def rebuild():
    """
    Deletes and re-creates your DB. Needs django-extensions and South.

    """
    drop_db()
    create_db()
    if StrictVersion(django.get_version()) < StrictVersion('1.7'):
        local('python{} manage.py syncdb --all --noinput'.format(
            PYTHON_VERSION))
        local('python{} manage.py migrate --fake'.format(PYTHON_VERSION))
    else:
        local('python{} manage.py migrate'.format(PYTHON_VERSION))

Example 4

Project: django-tablib Source File: __init__.py
Function: get_info
    def get_info(self):
        """
        Helper method to get model info in a form of (app_label, model_name).
        Avoid deprecation warnings and failures with different Django versions.
        """
        if LooseVersion(django.get_version()) < LooseVersion('1.7.0'):
            info = self.model._meta.app_label, self.model._meta.module_name
        else:
            info = self.model._meta.app_label, self.model._meta.model_name
        return info

Example 5

Project: django-filer Source File: migrations.py
Function: test_makemigrations
    @skipIf(django.get_version() < '1.7',
            'migrations not supported in django < 1.7')
    def test_makemigrations(self):
        out = StringIO()
        call_command('makemigrations', dry_run=True, noinput=True, stdout=out)
        output = out.getvalue()
        self.assertEqual(output, 'No changes detected\n')

Example 6

Project: data-importer Source File: test_base_model.py
    def test_errors_values(self):
        self.importer.is_valid()
        DJANGO_VERSION = StrictVersion(django.get_version())
        if DJANGO_VERSION < StrictVersion('1.4'):
            error = [(1, 'ValidationError', 'Field (price) This value must be a float.')]
        else:
            error = [(1, 'ValidationError', 'Field (price) 23,98 value must be a float.')]

        self.assertEquals(self.importer.errors, error, self.importer.cleaned_data)

Example 7

Project: pombola Source File: views.py
    def get(self, request, *args, **kwargs):
        result = {
            'python_version': sys.version,
            'django_version': django.get_version(),
        }
        # Try to get the object name of HEAD from git:
        try:
            git_version = subprocess.check_output(
                ['git', 'rev-parse', '--verify', 'HEAD'],
                cwd=dirname(__file__),
            ).strip()
            result['git_version'] = git_version
        except OSError, subprocess.CalledProcessError:
            pass

Example 8

Project: django-cache-manager Source File: mixins.py
Function: cache_backend
    @property
    def cache_backend(self):
        """
        Get the cache backend

        Returns
        ~~~~~~~
        Django cache backend

        """
        if not hasattr(self, '_cache_backend'):
            # determine django version for getting cache backend
            if django.get_version() >= '1.7':
                self._cache_backend = caches[_cache_name]
            else:
                self._cache_backend = get_cache(_cache_name)
        return self._cache_backend

Example 9

Project: opbeat_python Source File: client.py
Function: init
    def __init__(self, **kwargs):
        instrument_django_middleware = kwargs.pop(
            'instrument_django_middleware',
            None
        )
        if instrument_django_middleware is not None:
            self.instrument_django_middleware = instrument_django_middleware
        else:
            self.instrument_django_middleware = defaults.INSTRUMENT_DJANGO_MIDDLEWARE
        kwargs['framework_version'] = 'django/' + django.get_version()
        super(DjangoClient, self).__init__(**kwargs)

Example 10

Project: django-coupons Source File: test_admin.py
    @skipIf(StrictVersion(django.get_version()) < StrictVersion('1.7'), "Skip list display test due to missing method.")
    def test_list_display(self):
        admin = CouponAdmin(Coupon, self.site)

        self.assertEquals(
            list(admin.get_fields(request)),
            ['value', 'code', 'type', 'user_limit', 'valid_until', 'campaign']
        )

Example 11

Project: oq-engine Source File: functional_test.py
Function: setup_class
    @classmethod
    def setUpClass(cls):
        if django.get_version() < '1.5':
            # Django too old
            raise unittest.SkipTest('webui tests do not run with Diango < 1.5')

        cls.job_ids = []
        env = os.environ.copy()
        env['OQ_DISTRIBUTE'] = 'no'
        # let's impersonate the user openquake, the one running the WebUI:
        # we need to set LOGNAME on Linux and USERNAME on Windows
        env['LOGNAME'] = env['USERNAME'] = 'openquake'
        cls.fd, cls.errfname = tempfile.mkstemp(prefix='webui')
        print('Errors saved in %s' % cls.errfname, file=sys.stderr)
        cls.proc = subprocess.Popen(
            [sys.executable, '-m', 'openquake.server.manage', 'runserver',
             cls.hostport, '--noreload', '--nothreading'],
            env=env, stderr=cls.fd)  # redirect the server logs
        time.sleep(5)

Example 12

Project: 2buntu-blog Source File: views.py
def about(request):
    """
    Render the about page.
    """
    return render(request, 'pages/about.html', {
        'title': 'About Us',
        'num_articles': Article.objects.filter(status=Article.PUBLISHED).count(),
        'num_users': User.objects.filter(is_active=True).count(),
        'hostname': gethostname(),
        'django_version': get_version(),
        'python_version': python_version(),
        'commit': _commit,
    })

Example 13

Project: django-simple-history Source File: test_models.py
    @skipUnless(django.get_version() >= "1.7", "Requires 1.7 migrations")
    def test_migrations_include_order(self):
        from django.db.migrations import state
        model_state = state.ModelState.from_model(SeriesWork.history.model)
        found = False
        for name, field in model_state.fields:
            if name == '_order':
                found = True
                self.assertEqual(type(field), models.IntegerField)
        assert found, '_order not in fields ' + repr(model_state.fields)

Example 14

Project: django-db-mailer Source File: mail.py
    @staticmethod
    def _get_context_module_name(context):
        from distutils.version import StrictVersion
        import django

        current_version = django.get_version()

        if StrictVersion(current_version) < StrictVersion('1.8'):
            return context._meta.module_name
        return context._meta.model_name

Example 15

Project: GAE-Bulk-Mailer Source File: base.py
Function: get_version
    def get_version(self):
        """
        Return the Django version, which should be correct for all
        built-in Django commands. User-supplied commands should
        override this method.

        """
        return django.get_version()

Example 16

Project: mozilla-ignite Source File: sqlcreate.py
    @staticmethod
    def set_db_settings(**options):
        if django.get_version() >= "1.2":
            router = options.get('router')
            if router == None:
                return False

            # retrieve this with the 'using' argument
            dbinfo = settings.DATABASES.get(router)
            settings.DATABASE_ENGINE = dbinfo.get('ENGINE').split('.')[-1]
            settings.DATABASE_USER = dbinfo.get('USER')
            settings.DATABASE_PASSWORD = dbinfo.get('PASSWORD')
            settings.DATABASE_NAME = dbinfo.get('NAME')
            settings.DATABASE_HOST = dbinfo.get('HOST')
            settings.DATABASE_PORT = dbinfo.get('PORT')
            return True
        else:
            # settings are set for django < 1.2 no modification needed
            return True

Example 17

Project: django-cache-manager Source File: shared_memory.py
Function: cache_backend
    @property
    def cache_backend(self):
        if not hasattr(self, '_cache_backend'):
            if django.get_version() >= '1.7':
                self._cache_backend = caches[_cache_name]
            else:
                self._cache_backend = get_cache(_cache_name)

        return self._cache_backend

Example 18

Project: djangocms-helper Source File: test_commands.py
    @unittest.skipIf(LooseVersion(django.get_version()) > LooseVersion('1.8'),
                     reason='Test for Django up until 1.8')
    def test_cms_check_nocms(self):
        try:
            import cms
            raise unittest.SkipTest('django CMS available, skipping test')
        except ImportError:
            pass
        with work_in(self.basedir):
            with captured_output() as (out, err):
                shutil.copy(self.poexample, self.pofile)
                args = copy(DEFAULT_ARGS)
                args['cms_check'] = True
                args['--extra-settings'] = 'cms_helper.py'
                args['--migrate'] = False
                core(args, self.application)
            self.assertTrue('cms_check available only if django CMS is installed' in out.getvalue())

Example 19

Project: mozilla-ignite Source File: reset_db.py
    def set_db_settings(self, *args, **options):
        if django.get_version() >= "1.2":
            router = options.get('router')
            if router == None:
                return False

            # retrieve this with the 'using' argument
            dbinfo = settings.DATABASES.get(router)
            settings.DATABASE_ENGINE = dbinfo.get('ENGINE').split('.')[-1]
            settings.DATABASE_USER = dbinfo.get('USER')
            settings.DATABASE_PASSWORD = dbinfo.get('PASSWORD')
            settings.DATABASE_NAME = dbinfo.get('NAME')
            settings.DATABASE_HOST = dbinfo.get('HOST')
            settings.DATABASE_PORT = dbinfo.get('PORT')
            return True
        else:
            # settings are set for django < 1.2 no modification needed
            return True

Example 20

Project: django-statictemplate Source File: tests.py
    def setUp(self):
        super(StaticTemplateTests, self).setUp()
        if LooseVersion(django.get_version()) < LooseVersion('1.8'):
            settings.TEMPLATE_LOADERS = ['statictemplate.tests.TestLoader']
        else:
            settings.TEMPLATES[0]['OPTIONS']['loaders'] = ['statictemplate.tests.TestLoader']

Example 21

Project: djangocms-helper Source File: test_commands.py
    @unittest.skipIf(LooseVersion(django.get_version()) < LooseVersion('1.7'),
                     reason='makemigrations command available for Django 1.7+ only')
    def test_any_command_migrations(self):
        with work_in(self.basedir):
            with captured_output() as (out, err):
                args = copy(DEFAULT_ARGS)
                args['<command>'] = 'makemigrations'
                args['options'] = 'helper makemigrations example2 --verbosity=2'.split(' ')
                core(args, self.application)
            self.assertFalse('Create model ExampleModel1' in out.getvalue())
            self.assertFalse(os.path.exists(self.migration_file))
            self.assertTrue('Create model ExampleModel2' in out.getvalue())
            self.assertTrue(os.path.exists(self.migration_file_2))

Example 22

Project: django-compositepks Source File: base.py
Function: get_version
    def get_version(self):
        """
        Return the Django version, which should be correct for all
        built-in Django commands. User-supplied commands should
        override this method.
        
        """
        return django.get_version()

Example 23

Project: django-development-fabfile Source File: remote.py
@require_server
def run_syncdb():
    """
    Runs `./manage.py syncdb --migrate` on the given server.

    Usage::

        fab <server> run_syncdb

    """
    with cd(settings.FAB_SETTING('SERVER_PROJECT_ROOT')):
        if StrictVersion(django.get_version()) < StrictVersion('1.7'):
            run_workon('python{} manage.py syncdb --migrate --noinput'.format(
                PYTHON_VERSION))
        else:
            run_workon('python{} manage.py migrate'.format(PYTHON_VERSION))

Example 24

Project: django-oscar Source File: context_processors.py
def usage_statistics_string():
    """
    For Oscar development, it is helpful to know which versions of Oscar,
    Django and Python are in use, and which can be safely deprecated or
    removed. If tracking is enabled, this function builds a query string with
    that information. It is used in dashboard/layout.html with an invisible
    tracker pixel.
    If you're developing locally or tracking is disabled, the tracker pixel
    does not get rendered and no information is collected.
    """
    if not settings.DEBUG and getattr(settings, 'OSCAR_TRACKING', True):
        params = {
            'django': django.get_version(),
            'python': platform.python_version(),
            'oscar': oscar.get_version(),
        }
        return mark_safe(parse.urlencode(params))
    else:
        return None

Example 25

Project: talk.org Source File: base.py
Function: get_version
    def get_version(self):
        """
        Returns the Django version, which should be correct for all built-in
        Django commands. User-supplied commands should override this method.
        """
        return django.get_version()

Example 26

Project: django-click Source File: adapter.py
Function: init
    def __init__(self, **kwargs):
        self.kwargs = kwargs
        self.version = self.kwargs.pop('version', get_version())

        context_settings = kwargs.setdefault('context_settings', {})
        context_settings['help_option_names'] = ['-h', '--help']

Example 27

Project: django-lockdown Source File: tests.py
    def setUp(self):
        """Additional setup for middleware tests."""
        super(MiddlewareTests, self).setUp()
        if parse_version(django.get_version()) < parse_version('1.10'):
            self._old_middleware_classes = django_settings.MIDDLEWARE_CLASSES
            django_settings.MIDDLEWARE_CLASSES += (
                'lockdown.middleware.LockdownMiddleware',
            )
        else:
            self._old_middleware_classes = django_settings.MIDDLEWARE
            django_settings.MIDDLEWARE.append(
                'lockdown.middleware.LockdownMiddleware',
            )

Example 28

Project: djangocms-helper Source File: test_commands.py
    @unittest.skipIf(LooseVersion(django.get_version()) >= LooseVersion('1.7'),
                     reason='check only for Django < 1.7')
    def test_makemigrations_existing_folder(self):
        os.makedirs(self.migration_dir)
        os.makedirs(self.migration_dir_2)
        open(os.path.join(self.migration_dir, '__init__.py'), 'w')
        open(os.path.join(self.migration_dir_2, '__init__.py'), 'w')
        with work_in(self.basedir):
            with captured_output() as (out, err):
                args = copy(DEFAULT_ARGS)
                args['makemigrations'] = True
                args['<extra-applications>'] = ['example2']
                core(args, self.application)
            self.assertTrue(os.path.exists(self.migration_file))
            self.assertTrue(os.path.exists(self.migration_file_2))
        self.assertTrue('Created 0001_initial.py' in err.getvalue())
        self.assertTrue('migrate example1' in err.getvalue())
        self.assertTrue('migrate example2' in err.getvalue())

Example 29

Project: django-js-error-hook Source File: views.py
    def render_to_response(self, context, **response_kwargs):
        """
            Before django 1.5 : 'mimetype'
            From django 1.5 : 'content_type'

            Add the parameter to return the right mimetype
        """
        if StrictVersion(get_version()) < StrictVersion('1.5'):
            mimetype_parameter = 'mimetype'
        else:
            mimetype_parameter = 'content_type'

        response_kwargs[mimetype_parameter] = self.mimetype
        return super(MimetypeTemplateView, self).render_to_response(context, **response_kwargs)

Example 30

Project: talk.org Source File: __init__.py
Function: main_help_text
    def main_help_text(self):
        """
        Returns the script's main help text, as a string.
        """
        usage = ['%s <subcommand> [options] [args]' % self.prog_name]
        usage.append('Django command line tool, version %s' % django.get_version())
        usage.append("Type '%s help <subcommand>' for help on a specific subcommand." % self.prog_name)
        usage.append('Available subcommands:')
        commands = get_commands(self.user_commands, self.project_directory).keys()
        commands.sort()
        for cmd in commands:
            usage.append('  %s' % cmd)
        return '\n'.join(usage)

Example 31

Project: django-elasticsearch Source File: models.py
def es_syncdb_callback(sender, app=None, created_models=[], **kwargs):
    if int(get_version()[2]) > 6:
        models = sender.get_models()
    else:
        models = created_models
    
    for model in models:
        if issubclass(model, EsIndexable):
            model.es.create_index()

Example 32

Project: django-gunicorn Source File: config.py
Function: post_worker_init
def post_worker_init(worker):
    """Hook into Gunicorn to display message after launching.

    This mimics the behaviour of Django's stock runserver command.
    """
    quit_command = 'CTRL-BREAK' if sys.platform == 'win32' else 'CONTROL-C'
    sys.stdout.write(
        "Django version {djangover}, Gunicorn version {gunicornver}, "
        "using settings {settings!r}\n"
        "Starting development server at {urls}\n"
        "Quit the server with {quit_command}.\n".format(
            djangover=django.get_version(),
            gunicornver=gunicorn.__version__,
            settings=os.environ.get('DJANGO_SETTINGS_MODULE'),
            urls=', '.join('http://{0}/'.format(b) for b in worker.cfg.bind),
            quit_command=quit_command,
        ),
    )

Example 33

Project: func Source File: djangoctl.py
Function: environment
    def environment(self, project_path):
        """
        Gets the environment information that the project is running on.

        project_path is the path to the Django project.
        """
        self._verify_path(project_path)
        import platform
        from django import get_version

        return {'django_version': get_version(),
                'uname': platform.uname(),
                'dist': platform.dist(),
                'python_version': platform.python_version()}

Example 34

Project: muddery Source File: muddery_launcher.py
def show_version_info(about=False):
    """
    Display version info
    """
    import os, sys
    import twisted
    import django

    return VERSION_INFO.format(version=MUDDERY_VERSION,
                               about=ABOUT_INFO if about else "",
                               os=os.name, python=sys.version.split()[0],
                               twisted=twisted.version.short(),
                               django=django.get_version(),
                               evennia=evennia_launcher.evennia_version(),)

Example 35

Project: djangocms-helper Source File: test_commands.py
    @unittest.skipIf(LooseVersion(django.get_version()) < LooseVersion('1.9'),
                     reason='Test for Django 1.9+')
    def test_cms_check_nocms_19(self):
        try:
            import cms
            raise unittest.SkipTest('django CMS available, skipping test')
        except ImportError:
            pass
        with work_in(self.basedir):
            with self.assertRaises(ImportError):
                shutil.copy(self.poexample, self.pofile)
                args = copy(DEFAULT_ARGS)
                args['cms_check'] = True
                args['--extra-settings'] = 'cms_helper.py'
                args['--migrate'] = False
                core(args, self.application)

Example 36

Project: cgstudiomap Source File: base.py
Function: get_version
    def get_version(self):
        """
        Return the Django version, which should be correct for all built-in
        Django commands. User-supplied commands can override this method to
        return their own version.
        """
        return django.get_version()

Example 37

Project: django-el-pagination Source File: context_processors.py
Function: versions
def versions(request):
    """Add to context the version numbers of relevant apps."""
    values = (
        ('Python', platform.python_version()),
        ('Django', django.get_version()),
        ('EL Pagination', el_pagination.get_version()),
    )
    return {'versions': values}

Example 38

Project: django-lockdown Source File: tests.py
    def tearDown(self):
        """Additional tear down for middleware tests."""
        if parse_version(django.get_version()) < parse_version('1.10'):
            django_settings.MIDDLEWARE_CLASSES = self._old_middleware_classes
        else:
            django_settings.MIDDLEWARE = self._old_middleware_classes
        super(MiddlewareTests, self).tearDown()

Example 39

Project: django-cbv-inspector Source File: populate_cbv.py
    def handle(self, *args, **options):
        # Delete ALL of the things.
        ProjectVersion.objects.filter(
            project__name__iexact='Django',
            version_number=django.get_version(),
        ).delete()
        Inheritance.objects.filter(
            parent__module__project_version__project__name__iexact='Django',
            parent__module__project_version__version_number=django.get_version(),
        ).delete()

        # Setup Project
        self.project_version = ProjectVersion.objects.create(
            project=Project.objects.get_or_create(name='Django')[0],
            version_number=django.get_version(),
        )

        self.klasses = {}
        self.attributes = {}
        self.klass_imports = {}

        # Set sources appropriate to this version
        self.sources = []
        for source in settings.CBV_SOURCES.keys():
            try:
                self.sources.append(importlib.import_module(source))
            except ImportError:
                pass

        print t.red('Tree traversal')
        for source in self.sources:
            self.process_member(source, source.__name__)
        self.create_inheritance()
        self.create_attributes()

Example 40

Project: PyClassLessons Source File: __init__.py
    def execute(self):
        """
        Given the command-line arguments, this figures out which subcommand is
        being run, creates a parser appropriate to that command, and runs it.
        """
        # Preprocess options to extract --settings and --pythonpath.
        # These options could affect the commands that are available, so they
        # must be processed early.
        parser = LaxOptionParser(usage="%prog subcommand [options] [args]",
                                 version=get_version(),
                                 option_list=BaseCommand.option_list)
        try:
            options, args = parser.parse_args(self.argv)
            handle_default_options(options)
        except:  # Needed because parser.parse_args can raise SystemExit
            pass  # Ignore any option errors at this point.

        try:
            subcommand = self.argv[1]
        except IndexError:
            subcommand = 'help'  # Display help if no arguments were given.

        no_settings_commands = [
            'help', 'version', '--help', '--version', '-h',
            'compilemessages', 'makemessages',
            'startapp', 'startproject',
        ]

        try:
            settings.INSTALLED_APPS
        except ImproperlyConfigured as exc:
            self.settings_exception = exc
            # A handful of built-in management commands work without settings.
            # Load the default settings -- where INSTALLED_APPS is empty.
            if subcommand in no_settings_commands:
                settings.configure()

        if settings.configured:
            django.setup()

        self.autocomplete()

        if subcommand == 'help':
            if len(args) <= 2:
                parser.print_lax_help()
                sys.stdout.write(self.main_help_text() + '\n')
            elif args[2] == '--commands':
                sys.stdout.write(self.main_help_text(commands_only=True) + '\n')
            else:
                self.fetch_command(args[2]).print_help(self.prog_name, args[2])
        elif subcommand == 'version':
            sys.stdout.write(parser.get_version() + '\n')
        # Special-cases: We want 'django-admin.py --version' and
        # 'django-admin.py --help' to work, for backwards compatibility.
        elif self.argv[1:] == ['--version']:
            # LaxOptionParser already takes care of printing the version.
            pass
        elif self.argv[1:] in (['--help'], ['-h']):
            parser.print_lax_help()
            sys.stdout.write(self.main_help_text() + '\n')
        else:
            self.fetch_command(subcommand).run_from_argv(self.argv)

Example 41

Project: mezzanine Source File: runserver.py
def banner():

    # Database name - this is just the ``vendor`` atrribute of
    # the connection backend, with some exceptions where we
    # replace it with something else, such as microsoft -> sql server.
    conn = connection
    db_name = {
        "microsoft": "sql server",
    }.get(conn.vendor, conn.vendor)
    db_name = "%s%s" % (db_name[:1].upper(),
        db_name.replace("sql", "SQL").replace("db", "DB")[1:])

    # Database version - vendor names mapped to functions that
    # retrieve the version, which should be a sequence of things
    # to join with dots.
    db_version_func = {
        "postgresql": lambda: (
            conn.pg_version // 10000,
            conn.pg_version // 100 % 100,
            conn.pg_version % 100,
        ),
        "mysql": lambda: conn.mysql_version,
        "sqlite": lambda: conn.Database.sqlite_version_info,
        # The remaining backends haven't actually been tested,
        # and so their version logic has been gleaned from glancing
        # at the code for each backend.
        "oracle": lambda: [conn.oracle_version],
        "microsoft": lambda: [conn._DatabaseWrapper__get_dbms_version()],
        "firebird": lambda: conn.server_version.split(" ")[-1].split("."),
    }.get(conn.vendor, lambda: [])
    db_version = ".".join(map(str, db_version_func()))

    # The raw banner split into lines.
    lines = ("""

              .....
          _d^^^^^^^^^b_
       .d''           ``b.
     .p'                `q.
    .d'                   `b.
   .d'                     `b.   * Mezzanine %(mezzanine_version)s
   ::                       ::   * Django %(django_version)s
  ::    M E Z Z A N I N E    ::  * Python %(python_version)s
   ::                       ::   * %(db_name)s %(db_version)s
   `p.                     .q'   * %(os_name)s %(os_version)s
    `p.                   .q'
     `b.                 .d'
       `q..          ..p'
          ^q........p^
              ''''


""" % {
        "mezzanine_version": mezzanine.__version__,
        "django_version": django.get_version(),
        "python_version": sys.version.split(" ", 1)[0],
        "db_name": db_name,
        "db_version": db_version,
        "os_name": platform.system(),
        "os_version": platform.release(),
    }).splitlines()[2:]

    if not supports_color():
        return "\n".join(lines)

    # Pairs of function / colorize args for coloring the banner.
    # These are each of the states moving from left to right on
    # a single line of the banner. The function represents whether
    # the current char in a line should trigger the next state.
    color_states = [
        (lambda c: c != " ", {}),
        (lambda c: c == " ", {"fg": "red"}),
        (lambda c: c != " " and not c.isupper(),
            {"fg": "white", "bg": "red", "opts": ["bold"]}),
        (lambda c: c == " ", {"fg": "red"}),
        (lambda c: c == "*", {}),
        (lambda c: c != "*", {"fg": "red"}),
        (lambda c: False, {}),
    ]

    # Colorize the banner.
    for i, line in enumerate(lines):
        chars = []
        color_state = 0
        for char in line:
            color_state += color_states[color_state][0](char)
            chars.append(colorize(char, **color_states[color_state][1]))
        lines[i] = "".join(chars)

    return "\n".join(lines)

Example 42

Project: PyClassLessons Source File: debug.py
    def get_traceback_data(self):
        """Return a dictionary containing traceback information."""

        if self.exc_type and issubclass(self.exc_type, TemplateDoesNotExist):
            from django.template.loader import template_source_loaders
            self.template_does_not_exist = True
            self.loader_debug_info = []
            # If the template_source_loaders haven't been populated yet, you need
            # to provide an empty list for this for loop to not fail.
            if template_source_loaders is None:
                template_source_loaders = []
            for loader in template_source_loaders:
                try:
                    source_list_func = loader.get_template_sources
                    # NOTE: This assumes exc_value is the name of the template that
                    # the loader attempted to load.
                    template_list = [{
                        'name': t,
                        'status': self.format_path_status(t),
                    } for t in source_list_func(str(self.exc_value))]
                except AttributeError:
                    template_list = []
                loader_name = loader.__module__ + '.' + loader.__class__.__name__
                self.loader_debug_info.append({
                    'loader': loader_name,
                    'templates': template_list,
                })
        if (settings.TEMPLATE_DEBUG and
                hasattr(self.exc_value, 'django_template_source')):
            self.get_template_exception_info()

        frames = self.get_traceback_frames()
        for i, frame in enumerate(frames):
            if 'vars' in frame:
                frame['vars'] = [(k, force_escape(pprint(v))) for k, v in frame['vars']]
            frames[i] = frame

        unicode_hint = ''
        if self.exc_type and issubclass(self.exc_type, UnicodeError):
            start = getattr(self.exc_value, 'start', None)
            end = getattr(self.exc_value, 'end', None)
            if start is not None and end is not None:
                unicode_str = self.exc_value.args[1]
                unicode_hint = smart_text(unicode_str[max(start - 5, 0):min(end + 5, len(unicode_str))], 'ascii', errors='replace')
        from django import get_version
        c = {
            'is_email': self.is_email,
            'unicode_hint': unicode_hint,
            'frames': frames,
            'request': self.request,
            'filtered_POST': self.filter.get_post_parameters(self.request),
            'settings': get_safe_settings(),
            'sys_executable': sys.executable,
            'sys_version_info': '%d.%d.%d' % sys.version_info[0:3],
            'server_time': datetime.datetime.now(),
            'django_version_info': get_version(),
            'sys_path': sys.path,
            'template_info': self.template_info,
            'template_does_not_exist': self.template_does_not_exist,
            'loader_debug_info': self.loader_debug_info,
        }
        # Check whether exception info is available
        if self.exc_type:
            c['exception_type'] = self.exc_type.__name__
        if self.exc_value:
            c['exception_value'] = smart_text(self.exc_value, errors='replace')
        if frames:
            c['lastframe'] = frames[-1]
        return c

Example 43

Project: GAE-Bulk-Mailer Source File: __init__.py
Function: execute
    def execute(self):
        """
        Given the command-line arguments, this figures out which subcommand is
        being run, creates a parser appropriate to that command, and runs it.
        """
        # Preprocess options to extract --settings and --pythonpath.
        # These options could affect the commands that are available, so they
        # must be processed early.
        parser = LaxOptionParser(usage="%prog subcommand [options] [args]",
                                 version=get_version(),
                                 option_list=BaseCommand.option_list)
        self.autocomplete()
        try:
            options, args = parser.parse_args(self.argv)
            handle_default_options(options)
        except:
            pass # Ignore any option errors at this point.

        try:
            subcommand = self.argv[1]
        except IndexError:
            subcommand = 'help' # Display help if no arguments were given.

        if subcommand == 'help':
            if len(args) <= 2:
                parser.print_lax_help()
                sys.stdout.write(self.main_help_text() + '\n')
            elif args[2] == '--commands':
                sys.stdout.write(self.main_help_text(commands_only=True) + '\n')
            else:
                self.fetch_command(args[2]).print_help(self.prog_name, args[2])
        elif subcommand == 'version':
            sys.stdout.write(parser.get_version() + '\n')
        # Special-cases: We want 'django-admin.py --version' and
        # 'django-admin.py --help' to work, for backwards compatibility.
        elif self.argv[1:] == ['--version']:
            # LaxOptionParser already takes care of printing the version.
            pass
        elif self.argv[1:] in (['--help'], ['-h']):
            parser.print_lax_help()
            sys.stdout.write(self.main_help_text() + '\n')
        else:
            self.fetch_command(subcommand).run_from_argv(self.argv)

Example 44

Project: django-shop Source File: apps.py
def get_tuple_version(version=None):
    version = version or get_version()
    return tuple(map(lambda n: int(n), version.split('.')))

Example 45

Project: django-cbv-inspector Source File: populate_cbv.py
    def add_new_import_path(self, member, parent):
        import_path = parent.__name__
        try:
            current_import_path = self.klass_imports[member]
        except KeyError:
            self.klass_imports[member] = parent.__name__
        else:
            self.update_shortest_import_path(member, current_import_path, import_path)

        try:
            existing_member = Klass.objects.get(
                module__project_version__project__name__iexact='Django',
                module__project_version__version_number=django.get_version(),
                name=member.__name__)
        except Klass.DoesNotExist:
            return

        if self.update_shortest_import_path(member, existing_member.import_path, import_path):
            existing_member.import_path = import_path
            existing_member.save()

Example 46

Project: GAE-Bulk-Mailer Source File: debug.py
    def get_traceback_data(self):
        "Return a Context instance containing traceback information."

        if self.exc_type and issubclass(self.exc_type, TemplateDoesNotExist):
            from django.template.loader import template_source_loaders
            self.template_does_not_exist = True
            self.loader_debug_info = []
            for loader in template_source_loaders:
                try:
                    source_list_func = loader.get_template_sources
                    # NOTE: This assumes exc_value is the name of the template that
                    # the loader attempted to load.
                    template_list = [{'name': t, 'exists': os.path.exists(t)} \
                        for t in source_list_func(str(self.exc_value))]
                except AttributeError:
                    template_list = []
                loader_name = loader.__module__ + '.' + loader.__class__.__name__
                self.loader_debug_info.append({
                    'loader': loader_name,
                    'templates': template_list,
                })
        if (settings.TEMPLATE_DEBUG and
            hasattr(self.exc_value, 'django_template_source')):
            self.get_template_exception_info()

        frames = self.get_traceback_frames()
        for i, frame in enumerate(frames):
            if 'vars' in frame:
                frame['vars'] = [(k, force_escape(pprint(v))) for k, v in frame['vars']]
            frames[i] = frame

        unicode_hint = ''
        if self.exc_type and issubclass(self.exc_type, UnicodeError):
            start = getattr(self.exc_value, 'start', None)
            end = getattr(self.exc_value, 'end', None)
            if start is not None and end is not None:
                unicode_str = self.exc_value.args[1]
                unicode_hint = smart_text(unicode_str[max(start-5, 0):min(end+5, len(unicode_str))], 'ascii', errors='replace')
        from django import get_version
        c = {
            'is_email': self.is_email,
            'unicode_hint': unicode_hint,
            'frames': frames,
            'request': self.request,
            'filtered_POST': self.filter.get_post_parameters(self.request),
            'settings': get_safe_settings(),
            'sys_executable': sys.executable,
            'sys_version_info': '%d.%d.%d' % sys.version_info[0:3],
            'server_time': datetime.datetime.now(),
            'django_version_info': get_version(),
            'sys_path' : sys.path,
            'template_info': self.template_info,
            'template_does_not_exist': self.template_does_not_exist,
            'loader_debug_info': self.loader_debug_info,
        }
        # Check whether exception info is available
        if self.exc_type:
            c['exception_type'] = self.exc_type.__name__
        if self.exc_value:
            c['exception_value'] = smart_text(self.exc_value, errors='replace')
        if frames:
            c['lastframe'] = frames[-1]
        return c

Example 47

Project: django-tornado Source File: runtornado.py
Function: get
    def get(self):
        self.set_header("Content-Type", "text/plain;charset=utf-8")
        self.write("Tornado Web Server with Django %s" % django.get_version())
        self.finish()

Example 48

Project: talk.org Source File: debug.py
def get_traceback_html(request, exc_type, exc_value, tb):
    "Return HTML code for traceback."
    template_info = None
    template_does_not_exist = False
    loader_debug_info = None

    # Handle deprecated string exceptions
    if isinstance(exc_type, basestring):
        exc_value = Exception('Deprecated String Exception: %r' % exc_type)
        exc_type = type(exc_value)

    if issubclass(exc_type, TemplateDoesNotExist):
        from django.template.loader import template_source_loaders
        template_does_not_exist = True
        loader_debug_info = []
        for loader in template_source_loaders:
            try:
                source_list_func = getattr(__import__(loader.__module__, {}, {}, ['get_template_sources']), 'get_template_sources')
                # NOTE: This assumes exc_value is the name of the template that
                # the loader attempted to load.
                template_list = [{'name': t, 'exists': os.path.exists(t)} \
                    for t in source_list_func(str(exc_value))]
            except (ImportError, AttributeError):
                template_list = []
            loader_debug_info.append({
                'loader': loader.__module__ + '.' + loader.__name__,
                'templates': template_list,
            })
    if settings.TEMPLATE_DEBUG and hasattr(exc_value, 'source'):
        exc_type, exc_value, tb, template_info = get_template_exception_info(exc_type, exc_value, tb)
    frames = []
    while tb is not None:
        # support for __traceback_hide__ which is used by a few libraries
        # to hide internal frames.
        if tb.tb_frame.f_locals.get('__traceback_hide__'):
            tb = tb.tb_next
            continue
        filename = tb.tb_frame.f_code.co_filename
        function = tb.tb_frame.f_code.co_name
        lineno = tb.tb_lineno - 1
        loader = tb.tb_frame.f_globals.get('__loader__')
        module_name = tb.tb_frame.f_globals.get('__name__')
        pre_context_lineno, pre_context, context_line, post_context = _get_lines_from_file(filename, lineno, 7, loader, module_name)
        if pre_context_lineno is not None:
            frames.append({
                'tb': tb,
                'filename': filename,
                'function': function,
                'lineno': lineno + 1,
                'vars': tb.tb_frame.f_locals.items(),
                'id': id(tb),
                'pre_context': pre_context,
                'context_line': context_line,
                'post_context': post_context,
                'pre_context_lineno': pre_context_lineno + 1,
            })
        tb = tb.tb_next

    if not frames:
        frames = [{
            'filename': '<unknown>',
            'function': '?',
            'lineno': '?',
        }]

    unicode_hint = ''
    if issubclass(exc_type, UnicodeError):
        start = getattr(exc_value, 'start', None)
        end = getattr(exc_value, 'end', None)
        if start is not None and end is not None:
            unicode_str = exc_value.args[1]
            unicode_hint = smart_unicode(unicode_str[max(start-5, 0):min(end+5, len(unicode_str))], 'ascii', errors='replace')
    from django import get_version
    t = Template(TECHNICAL_500_TEMPLATE, name='Technical 500 template')
    c = Context({
        'exception_type': exc_type.__name__,
        'exception_value': smart_unicode(exc_value, errors='replace'),
        'unicode_hint': unicode_hint,
        'frames': frames,
        'lastframe': frames[-1],
        'request': request,
        'request_protocol': request.is_secure() and "https" or "http",
        'settings': get_safe_settings(),
        'sys_executable': sys.executable,
        'sys_version_info': '%d.%d.%d' % sys.version_info[0:3],
        'server_time': datetime.datetime.now(),
        'django_version_info': get_version(),
        'sys_path' : sys.path,
        'template_info': template_info,
        'template_does_not_exist': template_does_not_exist,
        'loader_debug_info': loader_debug_info,
    })
    return t.render(c)

Example 49

Project: edison Source File: utils.py
def format_error(error):
    return u"Piston/%s (Django %s) crash report:\n\n%s" % \
        (get_version(), django_version(), error)

Example 50

Project: Django--an-app-at-a-time Source File: debug.py
    def get_traceback_data(self):
        """Return a dictionary containing traceback information."""
        try:
            default_template_engine = Engine.get_default()
        except Exception:
            # Since the debug view must never crash, catch all exceptions.
            # If Django can't find a default template engine, get_default()
            # raises ImproperlyConfigured. If some template engines fail to
            # load, any exception may be raised.
            default_template_engine = None

        # TODO: add support for multiple template engines (#24120).
        # TemplateDoesNotExist should carry all the information.
        # Replaying the search process isn't a good design.
        if self.exc_type and issubclass(self.exc_type, TemplateDoesNotExist):
            if default_template_engine is None:
                template_loaders = []
            else:
                self.template_does_not_exist = True
                self.loader_debug_info = []
                # If Django fails in get_template_loaders, provide an empty list
                # for the following loop to not fail.
                try:
                    template_loaders = default_template_engine.template_loaders
                except Exception:
                    template_loaders = []

            for loader in template_loaders:
                try:
                    source_list_func = loader.get_template_sources
                    # NOTE: This assumes exc_value is the name of the template that
                    # the loader attempted to load.
                    template_list = [{
                        'name': t,
                        'status': self.format_path_status(t),
                    } for t in source_list_func(str(self.exc_value))]
                except AttributeError:
                    template_list = []
                loader_name = loader.__module__ + '.' + loader.__class__.__name__
                self.loader_debug_info.append({
                    'loader': loader_name,
                    'templates': template_list,
                })

        # TODO: add support for multiple template engines (#24119).
        if (default_template_engine is not None
                and default_template_engine.debug
                and hasattr(self.exc_value, 'django_template_source')):
            self.get_template_exception_info()

        frames = self.get_traceback_frames()
        for i, frame in enumerate(frames):
            if 'vars' in frame:
                frame_vars = []
                for k, v in frame['vars']:
                    v = pprint(v)
                    # The force_escape filter assume unicode, make sure that works
                    if isinstance(v, six.binary_type):
                        v = v.decode('utf-8', 'replace')  # don't choke on non-utf-8 input
                    # Trim large blobs of data
                    if len(v) > 4096:
                        v = '%s... <trimmed %d bytes string>' % (v[0:4096], len(v))
                    frame_vars.append((k, force_escape(v)))
                frame['vars'] = frame_vars
            frames[i] = frame

        unicode_hint = ''
        if self.exc_type and issubclass(self.exc_type, UnicodeError):
            start = getattr(self.exc_value, 'start', None)
            end = getattr(self.exc_value, 'end', None)
            if start is not None and end is not None:
                unicode_str = self.exc_value.args[1]
                unicode_hint = smart_text(
                    unicode_str[max(start - 5, 0):min(end + 5, len(unicode_str))],
                    'ascii', errors='replace'
                )
        from django import get_version
        c = {
            'is_email': self.is_email,
            'unicode_hint': unicode_hint,
            'frames': frames,
            'request': self.request,
            'filtered_POST': self.filter.get_post_parameters(self.request),
            'settings': get_safe_settings(),
            'sys_executable': sys.executable,
            'sys_version_info': '%d.%d.%d' % sys.version_info[0:3],
            'server_time': timezone.now(),
            'django_version_info': get_version(),
            'sys_path': sys.path,
            'template_info': self.template_info,
            'template_does_not_exist': self.template_does_not_exist,
            'loader_debug_info': self.loader_debug_info,
        }
        # Check whether exception info is available
        if self.exc_type:
            c['exception_type'] = self.exc_type.__name__
        if self.exc_value:
            c['exception_value'] = smart_text(self.exc_value, errors='replace')
        if frames:
            c['lastframe'] = frames[-1]
        return c
See More Examples - Go to Next Page
Page 1 Selected Page 2 Page 3