Python源码示例:django.VERSION

示例1
def sql_table_creation_suffix(self):
        suffix = []
        if django.VERSION < (1, 7):
            if self.connection.settings_dict['TEST_CHARSET']:
                suffix.append('CHARACTER SET {0}'.format(
                    self.connection.settings_dict['TEST_CHARSET']))
            if self.connection.settings_dict['TEST_COLLATION']:
                suffix.append('COLLATE {0}'.format(
                    self.connection.settings_dict['TEST_COLLATION']))

        else:
            test_settings = self.connection.settings_dict['TEST']
            if test_settings['CHARSET']:
                suffix.append('CHARACTER SET %s' % test_settings['CHARSET'])
            if test_settings['COLLATION']:
                suffix.append('COLLATE %s' % test_settings['COLLATION'])

        return ' '.join(suffix) 
示例2
def get_version(version=None):
    "Returns a PEP 386-compliant version number from VERSION."
    version = get_complete_version(version)

    # Now build the two parts of the version number:
    # major = X.Y[.Z]
    # sub = .devN - for pre-alpha releases
    #     | {a|b|c}N - for alpha, beta and rc releases

    major = get_major_version(version)

    sub = ''
    if version[3] == 'alpha' and version[4] == 0:
        git_changeset = get_git_changeset()
        if git_changeset:
            sub = '.dev%s' % git_changeset

    elif version[3] != 'final':
        mapping = {'alpha': 'a', 'beta': 'b', 'rc': 'c'}
        sub = mapping[version[3]] + str(version[4])

    return str(major + sub) 
示例3
def get_git_changeset():
    """Returns a numeric identifier of the latest git changeset.

    The result is the UTC timestamp of the changeset in YYYYMMDDHHMMSS format.
    This value isn't guaranteed to be unique, but collisions are very unlikely,
    so it's sufficient for generating the development version numbers.
    """
    repo_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    git_log = subprocess.Popen('git log --pretty=format:%ct --quiet -1 HEAD',
            stdout=subprocess.PIPE, stderr=subprocess.PIPE,
            shell=True, cwd=repo_dir, universal_newlines=True)
    timestamp = git_log.communicate()[0]
    try:
        timestamp = datetime.datetime.utcfromtimestamp(int(timestamp))
    except ValueError:
        return None
    return timestamp.strftime('%Y%m%d%H%M%S') 
示例4
def test_migration2(self):
        """Same test as test_migration, but this one passes."""
        MyModel = self.get_model_before('test_app.MyModel')
        self.assertEqual(MyModel.__name__, 'MyModel')

        self.run_migration()

        ForeignModel = self.get_model_after('test_app.ForeignModel')
        self.assertEqual(ForeignModel.__name__, 'ForeignModel')

        # get_model_before/get_model_after seems to not get the same model as
        # this crazy thing.
        if django.VERSION >= (2, 0):
            MyModel = ForeignModel.my.field.related_model
        else:
            MyModel = ForeignModel.my.field.rel.to
        self.assertEqual(MyModel.__name__, 'MyModel')

        my = MyModel(name='test_my', number=1, double_number=3.14)
        my.save()

        ForeignModel(name='test_foreign', my=my) 
示例5
def test_migration2(self):
        """Same test as test_migration, but this one passes."""
        MyModel = self.get_model_before('test_app.MyModel')
        self.assertEqual(MyModel.__name__, 'MyModel')

        self.run_migration()

        ForeignModel = self.get_model_after('test_app.ForeignModel')
        self.assertEqual(ForeignModel.__name__, 'ForeignModel')

        # get_model_before/get_model_after seems to not get the same model as
        # this crazy thing.
        if django.VERSION >= (2, 0):
            MyModel = ForeignModel.my.field.related_model
        else:
            MyModel = ForeignModel.my.field.rel.to
        self.assertEqual(MyModel.__name__, 'MyModel')

        my = MyModel(name='test_my', number=1, double_number=3.14)
        my.save()

        ForeignModel(name='test_foreign', my=my) 
示例6
def test_migration2(self):
        """Same test as test_migration, but this one passes."""
        MyModel = self.get_model_before('test_app.MyModel')
        self.assertEqual(MyModel.__name__, 'MyModel')

        self.run_migration()

        ForeignModel = self.get_model_after('test_app.ForeignModel')
        self.assertEqual(ForeignModel.__name__, 'ForeignModel')

        # get_model_before/get_model_after seems to not get the same model as
        # this crazy thing.
        if django.VERSION >= (2, 0):
            MyModel = ForeignModel.my.field.related_model
        else:
            MyModel = ForeignModel.my.field.rel.to
        self.assertEqual(MyModel.__name__, 'MyModel')

        my = MyModel(name='test_my', number=1, double_number=3.14)
        my.save()

        ForeignModel(name='test_foreign', my=my) 
示例7
def get_version(version=None):
    """Return a PEP 440-compliant version number from VERSION."""
    version = get_complete_version(version)

    # Now build the two parts of the version number:
    # main = X.Y[.Z]
    # sub = .devN - for pre-alpha releases
    #     | {a|b|rc}N - for alpha, beta, and rc releases

    main = get_main_version(version)

    sub = ''
    if version[3] == 'alpha' and version[4] == 0:
        git_changeset = get_git_changeset()
        if git_changeset:
            sub = '.dev%s' % git_changeset

    elif version[3] != 'final':
        mapping = {'alpha': 'a', 'beta': 'b', 'rc': 'rc'}
        sub = mapping[version[3]] + str(version[4])

    return main + sub 
示例8
def get_git_changeset():
    """Return a numeric identifier of the latest git changeset.

    The result is the UTC timestamp of the changeset in YYYYMMDDHHMMSS format.
    This value isn't guaranteed to be unique, but collisions are very unlikely,
    so it's sufficient for generating the development version numbers.
    """
    repo_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    git_log = subprocess.Popen(
        'git log --pretty=format:%ct --quiet -1 HEAD',
        stdout=subprocess.PIPE, stderr=subprocess.PIPE,
        shell=True, cwd=repo_dir, universal_newlines=True,
    )
    timestamp = git_log.communicate()[0]
    try:
        timestamp = datetime.datetime.utcfromtimestamp(int(timestamp))
    except ValueError:
        return None
    return timestamp.strftime('%Y%m%d%H%M%S') 
示例9
def content(self, value):
        workbook = None
        if not bool(value) or not len(value):  # Short-circuit to protect against empty querysets/empty lists/None, etc
            self._container = []
            return
        elif isinstance(value, list):
            workbook = self._serialize_list(value)
        elif isinstance(value, QuerySet):
            workbook = self._serialize_queryset(value)
        if django.VERSION < (1, 9):
            if isinstance(value, ValuesQuerySet):
                workbook = self._serialize_values_queryset(value)
        if workbook is None:
            raise ValueError('ExcelResponse accepts the following data types: list, dict, QuerySet, ValuesQuerySet')

        if self.force_csv:
            self['Content-Type'] = 'text/csv; charset=utf8'
            self['Content-Disposition'] = 'attachment;filename="{}.csv"'.format(self.output_filename)
            workbook.seek(0)
            workbook = self.make_bytes(workbook.getvalue())
        else:
            self['Content-Type'] = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
            self['Content-Disposition'] = 'attachment; filename="{}.xlsx"'.format(self.output_filename)
            workbook = save_virtual_workbook(workbook)
        self._container = [self.make_bytes(workbook)] 
示例10
def test_rollback__with_sid(self):
        """
        Test of rollback with transaction savepoint
        """
        @compat.commit_on_success
        def db_action():
            m = UnimportantThing(pk=3, importance=3)
            m.save()
            return m

        @compat.commit_on_success
        def db_action_with_rollback(m):
            m.importance = 5
            sid = django.db.transaction.savepoint()
            m.save()
            compat.rollback(None, sid)

        if django.VERSION < (1, 5):  # Rollback doesn't work with SQLite
            return

        m = db_action()
        db_action_with_rollback(m)
        self.assertEqual(UnimportantThing.objects.get(pk=3).importance, 3) 
示例11
def test_rollback__without_sid(self):
        """
        Test of rollback without transaction savepoint
        """
        @compat.commit_on_success
        def db_action():
            m = UnimportantThing(pk=4, importance=4)
            m.save()
            return m

        @compat.commit_on_success
        def db_action_with_rollback(m):
            m.importance = 5
            m.save()
            compat.rollback()

        if django.VERSION < (1, 8):  # Rollback doesn't work after .save() if an exception isn't thrown
            return

        m = db_action()
        db_action_with_rollback(m)
        self.assertEqual(UnimportantThing.objects.get(pk=4).importance, 4) 
示例12
def publisher_status(self, obj):
        if not self.has_publish_permission(self.request, obj):
            return ''

        template_name = 'publisher/change_list_publish_status.html'

        publish_btn = None
        if obj.is_dirty:
            publish_btn = reverse(self.publish_reverse, args=(obj.pk, ))

        t = loader.get_template(template_name)
        c = Context({
            'publish_btn': publish_btn,
        })
        if django.VERSION >= (1, 10):
            return t.render(c.flatten())
        else:
            return t.render(c) 
示例13
def publisher_publish(self, obj):
        template_name = 'publisher/change_list_publish.html'

        is_published = False
        if obj.publisher_linked and obj.is_draft:
            is_published = True

        t = loader.get_template(template_name)
        c = Context({
            'object': obj,
            'is_published': is_published,
            'has_publish_permission': self.has_publish_permission(self.request, obj),
            'publish_url': reverse(self.publish_reverse, args=(obj.pk, )),
            'unpublish_url': reverse(self.unpublish_reverse, args=(obj.pk, )),
        })
        if django.VERSION >= (1, 10):
            return t.render(c.flatten())
        else:
            return t.render(c) 
示例14
def _get_field_type(field):
    if isinstance(field, models.ForeignKey):
        if django.VERSION >= (2, 0):
            to = field.remote_field.model
            if isinstance(to, str):
                to = _resolve_model(field, to)
        else:
            to = field.rel.to
            if isinstance(to, str):
                to = _resolve_model(field, to)

        return u":type %s: %s to :class:`~%s.%s`" % (
            field.name,
            type(field).__name__,
            to.__module__,
            to.__name__,
        )
    else:
        return u":type %s: %s" % (field.name, type(field).__name__) 
示例15
def test_model_fields(self):
        lines = []
        simple_model_path = 'sphinxcontrib_django.tests.test_docstrings.SimpleModel'
        if django.VERSION < (3, 0):
            obj = DeferredAttribute(field_name='dummy_field', model=simple_model_path)
        else:
            model = import_string(simple_model_path)
            obj = DeferredAttribute(field=model._meta.get_field('dummy_field'))

        docstrings._improve_attribute_docs(obj, '{}.dummy_field'.format(simple_model_path), lines)
        self.assertEqual(
            lines,
            [
                "**Model field:** dummy field",
            ],
        ) 
示例16
def render_activity(context, activity, template_prefix='', missing_data_policy=LOG):
    if hasattr(activity, 'enriched') and not activity.enriched:
        handle_not_enriched_data(activity, missing_data_policy)
        return ''

    if template_prefix != '':
        template_prefix = '%s_' % template_prefix

    if 'activities' in activity:
        template_name = "activity/aggregated/%s%s.html" % (template_prefix, activity['verb'])
    else:
        template_name = "activity/%s%s.html" % (template_prefix, activity['verb'])

    tmpl = loader.get_template(template_name)
    context['activity'] = activity

    if django.VERSION < (1, 11):
        context = Context(context)
    elif isinstance(context, Context):
        context = context.flatten()

    return tmpl.render(context) 
示例17
def create_parser(self, progname, subcommand):
        """
        Called when run through `call_command`.
        """
        if DJANGO_VERSION >= (1, 10):
            return ArgumentParserAdapter()
        else:  # NOCOV
            return OptionParseAdapter() 
示例18
def handle(self, *args, **options):
        # Get blogpage content type
        blogpage_content_type, created = ContentType.objects.get_or_create(
            model='blogpage',
            app_label='puput',
            defaults={'name': 'page'} if DJANGO_VERSION < (1, 8) else {}
        )

        # Get root page
        rootpage = Page.objects.first()

        # Set site root page as root site page
        site = Site.objects.first()
        site.root_page = rootpage
        site.save()

        # Create example blog page
        blogpage = BlogPage(
            title="Blog",
            content_type=blogpage_content_type,
            slug='blog',
        )

        # Add blog page as a child for homepage
        rootpage.add_child(instance=blogpage)
        revision = blogpage.save_revision()
        revision.publish() 
示例19
def test_invalid_request(self):
        form = PayFastForm(initial={'amount': 100, 'item_name': 'foo'})
        notify_data = {'m_payment_id': form.order.m_payment_id}
        notify_data['signature'] = api.itn_signature(notify_data)
        response = self.client.post(notify_url(), notify_data)
        expected_amount = ('100' if django.VERSION < (1, 8) else
                           '100.00')
        self._assertBadRequest(response, {
            'amount_gross': [{'code': '', 'message': ('Amount is not the same: {} != None'
                                                      .format(expected_amount))}],
            'item_name': [{'code': 'required', 'message': 'This field is required.'}],
            'merchant_id': [{'code': 'required', 'message': 'This field is required.'}],
        })
        self.assertEqual(self.notify_handler_orders, [])

        order = _order()
        self.assertEqual(order.request_ip, '127.0.0.1')
        self.assertEqual(set(order.debug_info.split('|')), {
            'amount_gross: Amount is not the same: {} != None'.format(
                '100' if django.VERSION < (1, 8) else
                # Django 1.8+ returns more precise DecimalField values
                '100.00'
            ),
            'item_name: This field is required.',
            'merchant_id: This field is required.',
        })
        self.assertEqual(order.trusted, False) 
示例20
def runtests(*test_args):
    import django
    if django.VERSION >= (1, 7):
        django.setup()
    failures = NoseTestSuiteRunner(verbosity=2,
                                      interactive=True).run_tests(test_args)
    sys.exit(failures) 
示例21
def dv():
    return (
        str(django.VERSION[0])
        + '.'
        + str(django.VERSION[1])
        + '.'
        + str(django.VERSION[2])
    ) 
示例22
def test_values_tab_discard_action(self):
        config = self.database_configurations.first()

        self.mock_configuration_get.return_value = config

        details_url = self._get_url_with_arg(DETAIL_URL, config.id)
        url = details_url + '?tab=configuration_details__value'

        self._test_create_altered_config_params(config, url)

        # get the state of the configuration before discard action
        changed_configuration_values = \
            dict.copy(config_param_manager.get(self.request, config.id)
                      .get_configuration().values)

        res = self.client.post(url, {'action': u"values__discard_changes"})
        self.mock_configuration_get.assert_called_once_with(
            test.IsHttpRequest(), config.id)
        if django.VERSION >= (1, 9):
            url = settings.TESTSERVER + url
        self.assertRedirectsNoFollow(res, url)

        # get the state of the configuration after discard action
        restored_configuration_values = \
            dict.copy(config_param_manager.get(self.request, config.id)
                      .get_configuration().values)

        self.assertTrue(config_param_manager.dict_has_changes(
            changed_configuration_values, restored_configuration_values)) 
示例23
def test_values_tab_apply_action_exception(self):
        # NOTE(zhaochao) Please refer to the comment at the beginning of the
        # 'test_values_tab_apply_action' about not using copy.deepcopy() for
        # details.
        original_config = self.database_configurations.first()
        from troveclient.v1 import configurations
        config = configurations.Configuration(
            configurations.Configurations(None), original_config.to_dict())
        # Making sure the newly constructed config object is the same as
        # the original one.
        self.assertEqual(config, original_config)

        # setup the configuration parameter manager
        config_param_mgr = config_param_manager.ConfigParamManager(
            config.id)
        config_param_mgr.configuration = config
        config_param_mgr.original_configuration_values = \
            dict.copy(config.values)

        self.mock_get.return_value = config_param_mgr

        self.mock_configuration_update.side_effect = self.exceptions.trove

        details_url = self._get_url_with_arg(DETAIL_URL, config.id)
        url = details_url + '?tab=configuration_details__value'

        self._test_create_altered_config_params(config, url)

        # apply changes
        res = self.client.post(url, {'action': u"values__apply_changes"})
        self.assert_mock_multiple_calls_with_same_arguments(
            self.mock_get, 11, mock.call(test.IsHttpRequest(), config.id))
        self.mock_configuration_update.assert_called_once_with(
            test.IsHttpRequest(),
            config.id,
            config_param_mgr.to_json())
        if django.VERSION >= (1, 9):
            url = settings.TESTSERVER + url
        self.assertRedirectsNoFollow(res, url)
        self.assertEqual(res.status_code, 302) 
示例24
def __init__(self, connection):
        super(DatabaseCreation, self).__init__(connection)

        if django.VERSION < (1, 8):
            self.data_types = {
                'AutoField': 'integer AUTO_INCREMENT',
                'BinaryField': 'longblob',
                'BooleanField': 'bool',
                'CharField': 'varchar(%(max_length)s)',
                'CommaSeparatedIntegerField': 'varchar(%(max_length)s)',
                'DateField': 'date',
                'DateTimeField': 'datetime',  # ms support set later
                'DecimalField': 'numeric(%(max_digits)s, %(decimal_places)s)',
                'FileField': 'varchar(%(max_length)s)',
                'FilePathField': 'varchar(%(max_length)s)',
                'FloatField': 'double precision',
                'IntegerField': 'integer',
                'BigIntegerField': 'bigint',
                'IPAddressField': 'char(15)',

                'GenericIPAddressField': 'char(39)',
                'NullBooleanField': 'bool',
                'OneToOneField': 'integer',
                'PositiveIntegerField': 'integer UNSIGNED',
                'PositiveSmallIntegerField': 'smallint UNSIGNED',
                'SlugField': 'varchar(%(max_length)s)',
                'SmallIntegerField': 'smallint',
                'TextField': 'longtext',
                'TimeField': 'time',  # ms support set later
            }

            # Support for microseconds
            if self.connection.mysql_version >= (5, 6, 4):
                self.data_types.update({
                    'DateTimeField': 'datetime(6)',
                    'TimeField': 'time(6)',
                }) 
示例25
def enable_constraint_checking(self):
        """Re-enable foreign key checks

        Re-enable foreign key checks after they have been disabled.
        """
        # Override needs_rollback in case constraint_checks_disabled is
        # nested inside transaction.atomic.
        if django.VERSION >= (1, 6):
            self.needs_rollback, needs_rollback = False, self.needs_rollback
        try:
            self.cursor().execute('SET @@session.foreign_key_checks = 1')
        finally:
            if django.VERSION >= (1, 6):
                self.needs_rollback = needs_rollback 
示例26
def get_table_list(self, cursor):
        """Returns a list of table names in the current database."""
        cursor.execute("SHOW FULL TABLES")
        if django.VERSION >= (1, 8):
            return [
                TableInfo(row[0], {'BASE TABLE': 't', 'VIEW': 'v'}.get(row[1]))
                for row in cursor.fetchall()
                ]
        else:
            return [row[0] for row in cursor.fetchall()] 
示例27
def get_table_description(self, cursor, table_name):
            """
            Returns a description of the table, with the DB-API
            cursor.description interface.
            """
            # varchar length returned by cursor.description is an internal
            # length not visible length (#5725), use information_schema database
            #  to fix this
            cursor.execute(
                "SELECT column_name, character_maximum_length "
                "FROM INFORMATION_SCHEMA.COLUMNS "
                "WHERE table_name = %s AND table_schema = DATABASE() "
                "AND character_maximum_length IS NOT NULL", [table_name])
            length_map = dict(cursor.fetchall())

            # Also getting precision and scale from
            # information_schema (see #5014)
            cursor.execute(
                "SELECT column_name, numeric_precision, numeric_scale FROM "
                "INFORMATION_SCHEMA.COLUMNS WHERE table_name = %s AND "
                "table_schema = DATABASE() AND data_type='decimal'",
                [table_name])
            numeric_map = dict((line[0], tuple([int(n) for n in line[1:]]))
                               for line in cursor.fetchall())

            cursor.execute("SELECT * FROM {0} LIMIT 1".format(
                self.connection.ops.quote_name(table_name)))

            if django.VERSION >= (1, 6):
                return [FieldInfo(*((force_text(line[0]),)
                                    + line[1:3]
                                    + (length_map.get(line[0], line[3]),)
                                    + numeric_map.get(line[0], line[4:6])
                                    + (line[6],)))
                        for line in cursor.description]
            else:
                return [
                    line[:3] + (length_map.get(line[0], line[3]),) + line[4:]
                    for line in cursor.description
                    ] 
示例28
def force_no_ordering(self):
        """
        "ORDER BY NULL" prevents MySQL from implicitly ordering by grouped
        columns. If no ordering would otherwise be applied, we don't want any
        implicit sorting going on.
        """
        if django.VERSION >= (1, 8):
            return [(None, ("NULL", [], False))]
        else:
            return ["NULL"] 
示例29
def is_authenticated(user):
    """
    Return whether or not a User is authenticated.
    Function provides compatibility following deprecation of method call to
    is_authenticated() in Django 2.0.
    """

    if django.VERSION < (1, 10):
        return user.is_authenticated()
    else:
        return user.is_authenticated 
示例30
def get_user_model():
    if django.VERSION >= (1, 5):
        from django.contrib.auth import get_user_model as _get_user_model
        User = _get_user_model()
    else:
        from django.contrib.auth.models import User
    return User