Python warnings.append() Examples

The following are 22 code examples of warnings.append(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module warnings , or try the search function .
Example #1
Source File: utils.py    From jarvis with GNU General Public License v2.0 6 votes vote down vote up
def do_encrypt(self, secret, use_encrypt=False, handler=None, context=None, **settings):
        """call handler's hash() method with specified options"""
        self.populate_settings(settings)
        if context is None:
            context = {}
        secret = self.populate_context(secret, context)
        if use_encrypt:
            # use legacy 1.6 api
            warnings = []
            if settings:
                context.update(**settings)
                warnings.append("passing settings to.*is deprecated")
            with self.assertWarningList(warnings):
                return (handler or self.handler).encrypt(secret, **context)
        else:
            # use 1.7 api
            return (handler or self.handler).using(**settings).hash(secret, **context) 
Example #2
Source File: related.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def get_instance_value_for_fields(instance, fields):
        ret = []
        opts = instance._meta
        for field in fields:
            # Gotcha: in some cases (like fixture loading) a model can have
            # different values in parent_ptr_id and parent's id. So, use
            # instance.pk (that is, parent_ptr_id) when asked for instance.id.
            if field.primary_key:
                possible_parent_link = opts.get_ancestor_link(field.model)
                if (not possible_parent_link or
                        possible_parent_link.primary_key or
                        possible_parent_link.model._meta.abstract):
                    ret.append(instance.pk)
                    continue
            ret.append(getattr(instance, field.attname))
        return tuple(ret) 
Example #3
Source File: utils.py    From jarvis with GNU General Public License v2.0 6 votes vote down vote up
def mktemp(self, *args, **kwds):
        """create temp file that's cleaned up at end of test"""
        self.require_writeable_filesystem()
        fd, path = tempfile.mkstemp(*args, **kwds)
        os.close(fd)
        queue = self._mktemp_queue
        if queue is None:
            queue = self._mktemp_queue = []
            def cleaner():
                for path in queue:
                    if os.path.exists(path):
                        os.remove(path)
                del queue[:]
            self.addCleanup(cleaner)
        queue.append(path)
        return path 
Example #4
Source File: related.py    From python2017 with MIT License 6 votes vote down vote up
def get_instance_value_for_fields(instance, fields):
        ret = []
        opts = instance._meta
        for field in fields:
            # Gotcha: in some cases (like fixture loading) a model can have
            # different values in parent_ptr_id and parent's id. So, use
            # instance.pk (that is, parent_ptr_id) when asked for instance.id.
            if field.primary_key:
                possible_parent_link = opts.get_ancestor_link(field.model)
                if (not possible_parent_link or
                        possible_parent_link.primary_key or
                        possible_parent_link.model._meta.abstract):
                    ret.append(instance.pk)
                    continue
            ret.append(getattr(instance, field.attname))
        return tuple(ret) 
Example #5
Source File: related.py    From python with Apache License 2.0 6 votes vote down vote up
def _check_to_fields_exist(self):
        # Skip nonexistent models.
        if isinstance(self.remote_field.model, six.string_types):
            return []

        errors = []
        for to_field in self.to_fields:
            if to_field:
                try:
                    self.remote_field.model._meta.get_field(to_field)
                except exceptions.FieldDoesNotExist:
                    errors.append(
                        checks.Error(
                            "The to_field '%s' doesn't exist on the related "
                            "model '%s'."
                            % (to_field, self.remote_field.model._meta.label),
                            obj=self,
                            id='fields.E312',
                        )
                    )
        return errors 
Example #6
Source File: related.py    From python with Apache License 2.0 6 votes vote down vote up
def get_instance_value_for_fields(instance, fields):
        ret = []
        opts = instance._meta
        for field in fields:
            # Gotcha: in some cases (like fixture loading) a model can have
            # different values in parent_ptr_id and parent's id. So, use
            # instance.pk (that is, parent_ptr_id) when asked for instance.id.
            if field.primary_key:
                possible_parent_link = opts.get_ancestor_link(field.model)
                if (not possible_parent_link or
                        possible_parent_link.primary_key or
                        possible_parent_link.model._meta.abstract):
                    ret.append(instance.pk)
                    continue
            ret.append(getattr(instance, field.attname))
        return tuple(ret) 
Example #7
Source File: related.py    From python2017 with MIT License 6 votes vote down vote up
def _check_to_fields_exist(self):
        # Skip nonexistent models.
        if isinstance(self.remote_field.model, six.string_types):
            return []

        errors = []
        for to_field in self.to_fields:
            if to_field:
                try:
                    self.remote_field.model._meta.get_field(to_field)
                except exceptions.FieldDoesNotExist:
                    errors.append(
                        checks.Error(
                            "The to_field '%s' doesn't exist on the related "
                            "model '%s'."
                            % (to_field, self.remote_field.model._meta.label),
                            obj=self,
                            id='fields.E312',
                        )
                    )
        return errors 
Example #8
Source File: related.py    From openhgsenti with Apache License 2.0 6 votes vote down vote up
def get_instance_value_for_fields(instance, fields):
        ret = []
        opts = instance._meta
        for field in fields:
            # Gotcha: in some cases (like fixture loading) a model can have
            # different values in parent_ptr_id and parent's id. So, use
            # instance.pk (that is, parent_ptr_id) when asked for instance.id.
            if field.primary_key:
                possible_parent_link = opts.get_ancestor_link(field.model)
                if (not possible_parent_link or
                        possible_parent_link.primary_key or
                        possible_parent_link.model._meta.abstract):
                    ret.append(instance.pk)
                    continue
            ret.append(getattr(instance, field.attname))
        return tuple(ret) 
Example #9
Source File: related.py    From openhgsenti with Apache License 2.0 6 votes vote down vote up
def _check_ignored_options(self, **kwargs):
        warnings = []

        if self.has_null_arg:
            warnings.append(
                checks.Warning(
                    'null has no effect on ManyToManyField.',
                    hint=None,
                    obj=self,
                    id='fields.W340',
                )
            )

        if len(self._validators) > 0:
            warnings.append(
                checks.Warning(
                    'ManyToManyField does not support validators.',
                    hint=None,
                    obj=self,
                    id='fields.W341',
                )
            )

        return warnings 
Example #10
Source File: utils.py    From jarvis with GNU General Public License v2.0 5 votes vote down vote up
def get_fuzz_verifiers(self, threaded=False):
        """return list of password verifiers (including external libs)

        used by fuzz testing.
        verifiers should be callable with signature
        ``func(password: unicode, hash: ascii str) -> ok: bool``.
        """
        handler = self.handler
        verifiers = []

        # call all methods starting with prefix in order to create
        for method_name in self.fuzz_verifiers:
            func = getattr(self, method_name)()
            if func is not None:
                verifiers.append(func)

        # create verifiers for any other available backends
        # NOTE: skipping this under threading test,
        #       since backend switching isn't threadsafe (yet)
        if hasattr(handler, "backends") and TEST_MODE("full") and not threaded:
            def maker(backend):
                def func(secret, hash):
                    orig_backend = handler.get_backend()
                    try:
                        handler.set_backend(backend)
                        return handler.verify(secret, hash)
                    finally:
                        handler.set_backend(orig_backend)
                func.__name__ = "check_" + backend + "_backend"
                func.__doc__ = backend + "-backend"
                return func
            for backend in iter_alt_backends(handler):
                verifiers.append(maker(backend))

        return verifiers 
Example #11
Source File: related.py    From python2017 with MIT License 5 votes vote down vote up
def contribute_to_related_class(self, cls, related):
        # Internal FK's - i.e., those with a related name ending with '+' -
        # and swapped models don't get a related descriptor.
        if not self.remote_field.is_hidden() and not related.related_model._meta.swapped:
            setattr(cls._meta.concrete_model, related.get_accessor_name(), self.related_accessor_class(related))
            # While 'limit_choices_to' might be a callable, simply pass
            # it along for later - this is too early because it's still
            # model load time.
            if self.remote_field.limit_choices_to:
                cls._meta.related_fkey_lookups.append(self.remote_field.limit_choices_to) 
Example #12
Source File: related.py    From python2017 with MIT License 5 votes vote down vote up
def resolve_related_fields(self):
        if len(self.from_fields) < 1 or len(self.from_fields) != len(self.to_fields):
            raise ValueError('Foreign Object from and to fields must be the same non-zero length')
        if isinstance(self.remote_field.model, six.string_types):
            raise ValueError('Related model %r cannot be resolved' % self.remote_field.model)
        related_fields = []
        for index in range(len(self.from_fields)):
            from_field_name = self.from_fields[index]
            to_field_name = self.to_fields[index]
            from_field = (self if from_field_name == 'self'
                          else self.opts.get_field(from_field_name))
            to_field = (self.remote_field.model._meta.pk if to_field_name is None
                        else self.remote_field.model._meta.get_field(to_field_name))
            related_fields.append((from_field, to_field))
        return related_fields 
Example #13
Source File: related.py    From python2017 with MIT License 5 votes vote down vote up
def _check_related_query_name_is_valid(self):
        if self.remote_field.is_hidden():
            return []
        rel_query_name = self.related_query_name()
        errors = []
        if rel_query_name.endswith('_'):
            errors.append(
                checks.Error(
                    "Reverse query name '%s' must not end with an underscore."
                    % (rel_query_name,),
                    hint=("Add or change a related_name or related_query_name "
                          "argument for this field."),
                    obj=self,
                    id='fields.E308',
                )
            )
        if LOOKUP_SEP in rel_query_name:
            errors.append(
                checks.Error(
                    "Reverse query name '%s' must not contain '%s'."
                    % (rel_query_name, LOOKUP_SEP),
                    hint=("Add or change a related_name or related_query_name "
                          "argument for this field."),
                    obj=self,
                    id='fields.E309',
                )
            )
        return errors 
Example #14
Source File: related.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def contribute_to_related_class(self, cls, related):
        # Internal FK's - i.e., those with a related name ending with '+' -
        # and swapped models don't get a related descriptor.
        if not self.remote_field.is_hidden() and not related.related_model._meta.swapped:
            setattr(cls, related.get_accessor_name(), self.related_accessor_class(related))
            # While 'limit_choices_to' might be a callable, simply pass
            # it along for later - this is too early because it's still
            # model load time.
            if self.remote_field.limit_choices_to:
                cls._meta.related_fkey_lookups.append(self.remote_field.limit_choices_to) 
Example #15
Source File: related.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def resolve_related_fields(self):
        if len(self.from_fields) < 1 or len(self.from_fields) != len(self.to_fields):
            raise ValueError('Foreign Object from and to fields must be the same non-zero length')
        if isinstance(self.remote_field.model, six.string_types):
            raise ValueError('Related model %r cannot be resolved' % self.remote_field.model)
        related_fields = []
        for index in range(len(self.from_fields)):
            from_field_name = self.from_fields[index]
            to_field_name = self.to_fields[index]
            from_field = (self if from_field_name == 'self'
                          else self.opts.get_field(from_field_name))
            to_field = (self.remote_field.model._meta.pk if to_field_name is None
                        else self.remote_field.model._meta.get_field(to_field_name))
            related_fields.append((from_field, to_field))
        return related_fields 
Example #16
Source File: related.py    From python with Apache License 2.0 5 votes vote down vote up
def contribute_to_related_class(self, cls, related):
        # Internal FK's - i.e., those with a related name ending with '+' -
        # and swapped models don't get a related descriptor.
        if not self.remote_field.is_hidden() and not related.related_model._meta.swapped:
            setattr(cls._meta.concrete_model, related.get_accessor_name(), self.related_accessor_class(related))
            # While 'limit_choices_to' might be a callable, simply pass
            # it along for later - this is too early because it's still
            # model load time.
            if self.remote_field.limit_choices_to:
                cls._meta.related_fkey_lookups.append(self.remote_field.limit_choices_to) 
Example #17
Source File: related.py    From python with Apache License 2.0 5 votes vote down vote up
def resolve_related_fields(self):
        if len(self.from_fields) < 1 or len(self.from_fields) != len(self.to_fields):
            raise ValueError('Foreign Object from and to fields must be the same non-zero length')
        if isinstance(self.remote_field.model, six.string_types):
            raise ValueError('Related model %r cannot be resolved' % self.remote_field.model)
        related_fields = []
        for index in range(len(self.from_fields)):
            from_field_name = self.from_fields[index]
            to_field_name = self.to_fields[index]
            from_field = (self if from_field_name == 'self'
                          else self.opts.get_field(from_field_name))
            to_field = (self.remote_field.model._meta.pk if to_field_name is None
                        else self.remote_field.model._meta.get_field(to_field_name))
            related_fields.append((from_field, to_field))
        return related_fields 
Example #18
Source File: related.py    From python with Apache License 2.0 5 votes vote down vote up
def _check_related_query_name_is_valid(self):
        if self.remote_field.is_hidden():
            return []
        rel_query_name = self.related_query_name()
        errors = []
        if rel_query_name.endswith('_'):
            errors.append(
                checks.Error(
                    "Reverse query name '%s' must not end with an underscore."
                    % (rel_query_name,),
                    hint=("Add or change a related_name or related_query_name "
                          "argument for this field."),
                    obj=self,
                    id='fields.E308',
                )
            )
        if LOOKUP_SEP in rel_query_name:
            errors.append(
                checks.Error(
                    "Reverse query name '%s' must not contain '%s'."
                    % (rel_query_name, LOOKUP_SEP),
                    hint=("Add or change a related_name or related_query_name "
                          "argument for this field."),
                    obj=self,
                    id='fields.E309',
                )
            )
        return errors 
Example #19
Source File: related.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def contribute_to_related_class(self, cls, related):
        # Internal FK's - i.e., those with a related name ending with '+' -
        # and swapped models don't get a related descriptor.
        if not self.rel.is_hidden() and not related.related_model._meta.swapped:
            setattr(cls, related.get_accessor_name(), self.related_accessor_class(related))
            # While 'limit_choices_to' might be a callable, simply pass
            # it along for later - this is too early because it's still
            # model load time.
            if self.rel.limit_choices_to:
                cls._meta.related_fkey_lookups.append(self.rel.limit_choices_to) 
Example #20
Source File: related.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def resolve_related_fields(self):
        if len(self.from_fields) < 1 or len(self.from_fields) != len(self.to_fields):
            raise ValueError('Foreign Object from and to fields must be the same non-zero length')
        if isinstance(self.rel.to, six.string_types):
            raise ValueError('Related model %r cannot be resolved' % self.rel.to)
        related_fields = []
        for index in range(len(self.from_fields)):
            from_field_name = self.from_fields[index]
            to_field_name = self.to_fields[index]
            from_field = (self if from_field_name == 'self'
                          else self.opts.get_field(from_field_name))
            to_field = (self.rel.to._meta.pk if to_field_name is None
                        else self.rel.to._meta.get_field(to_field_name))
            related_fields.append((from_field, to_field))
        return related_fields 
Example #21
Source File: related.py    From GTDWeb with GNU General Public License v2.0 4 votes vote down vote up
def get_lookup_constraint(self, constraint_class, alias, targets, sources, lookups,
                              raw_value):
        from django.db.models.sql.where import SubqueryConstraint, AND, OR
        root_constraint = constraint_class()
        assert len(targets) == len(sources)
        if len(lookups) > 1:
            raise exceptions.FieldError('Relation fields do not support nested lookups')
        lookup_type = lookups[0]

        def get_normalized_value(value):
            from django.db.models import Model
            if isinstance(value, Model):
                value_list = []
                for source in sources:
                    # Account for one-to-one relations when sent a different model
                    while not isinstance(value, source.model) and source.rel:
                        source = source.rel.to._meta.get_field(source.rel.field_name)
                    value_list.append(getattr(value, source.attname))
                return tuple(value_list)
            elif not isinstance(value, tuple):
                return (value,)
            return value

        is_multicolumn = len(self.related_fields) > 1
        if (hasattr(raw_value, '_as_sql') or
                hasattr(raw_value, 'get_compiler')):
            root_constraint.add(SubqueryConstraint(alias, [target.column for target in targets],
                                                   [source.name for source in sources], raw_value),
                                AND)
        elif lookup_type == 'isnull':
            root_constraint.add(IsNull(targets[0].get_col(alias, sources[0]), raw_value), AND)
        elif (lookup_type == 'exact' or (lookup_type in ['gt', 'lt', 'gte', 'lte']
                                         and not is_multicolumn)):
            value = get_normalized_value(raw_value)
            for target, source, val in zip(targets, sources, value):
                lookup_class = target.get_lookup(lookup_type)
                root_constraint.add(
                    lookup_class(target.get_col(alias, source), val), AND)
        elif lookup_type in ['range', 'in'] and not is_multicolumn:
            values = [get_normalized_value(value) for value in raw_value]
            value = [val[0] for val in values]
            lookup_class = targets[0].get_lookup(lookup_type)
            root_constraint.add(lookup_class(targets[0].get_col(alias, sources[0]), value), AND)
        elif lookup_type == 'in':
            values = [get_normalized_value(value) for value in raw_value]
            for value in values:
                value_constraint = constraint_class()
                for source, target, val in zip(sources, targets, value):
                    lookup_class = target.get_lookup('exact')
                    lookup = lookup_class(target.get_col(alias, source), val)
                    value_constraint.add(lookup, AND)
                root_constraint.add(value_constraint, OR)
        else:
            raise TypeError('Related Field got invalid lookup: %s' % lookup_type)
        return root_constraint 
Example #22
Source File: related.py    From GTDWeb with GNU General Public License v2.0 4 votes vote down vote up
def add_lazy_relation(cls, field, relation, operation):
    """
    Adds a lookup on ``cls`` when a related field is defined using a string,
    i.e.::

        class MyModel(Model):
            fk = ForeignKey("AnotherModel")

    This string can be:

        * RECURSIVE_RELATIONSHIP_CONSTANT (i.e. "self") to indicate a recursive
          relation.

        * The name of a model (i.e "AnotherModel") to indicate another model in
          the same app.

        * An app-label and model name (i.e. "someapp.AnotherModel") to indicate
          another model in a different app.

    If the other model hasn't yet been loaded -- almost a given if you're using
    lazy relationships -- then the relation won't be set up until the
    class_prepared signal fires at the end of model initialization.

    operation is the work that must be performed once the relation can be resolved.
    """
    # Check for recursive relations
    if relation == RECURSIVE_RELATIONSHIP_CONSTANT:
        app_label = cls._meta.app_label
        model_name = cls.__name__

    else:
        # Look for an "app.Model" relation

        if isinstance(relation, six.string_types):
            try:
                app_label, model_name = relation.split(".")
            except ValueError:
                # If we can't split, assume a model in current app
                app_label = cls._meta.app_label
                model_name = relation
        else:
            # it's actually a model class
            app_label = relation._meta.app_label
            model_name = relation._meta.object_name

    # Try to look up the related model, and if it's already loaded resolve the
    # string right away. If get_registered_model raises a LookupError, it means
    # that the related model isn't loaded yet, so we need to pend the relation
    # until the class is prepared.
    try:
        model = cls._meta.apps.get_registered_model(app_label, model_name)
    except LookupError:
        key = (app_label, model_name)
        value = (cls, field, operation)
        cls._meta.apps._pending_lookups.setdefault(key, []).append(value)
    else:
        operation(field, model, cls)