Takes the `query` and `response` fields from a validated config
        dictionary and sets the proper instance attributes.
171011
def apply_check_config(self, config):
        
        self.query = config.get("query")
        self.expected_response = config.get("response")
372381
def _instantiate_model(self, response, attrs, additional_properties=None):
        
        if callable(response):
            subtype = getattr(response, '_subtype_map', {})
            try:
                readonly = [k for k, v in response._validation.items()
                            if v.get('readonly')]
                const = [k for k, v in response._validation.items()
                         if v.get('constant')]
                kwargs = {k: v for k, v in attrs.items()
                          if k not in subtype and k not in readonly + const}
                response_obj = response(**kwargs)
                for attr in readonly:
                    setattr(response_obj, attr, attrs.get(attr))
                if additional_properties:
                    response_obj.additional_properties = additional_properties
                return response_obj
            except TypeError as err:
                msg = "Unable to deserialize {} into model {}. ".format(
                    kwargs, response)
                raise DeserializationError(msg + str(err))
        else:
            try:
                for attr, value in attrs.items():
                    setattr(response, attr, value)
                return response
            except Exception as exp:
                msg = "Unable to populate response model. "
                msg += "Type: {}, Error: {}".format(type(response), exp)
                raise DeserializationError(msg)
975891
def prepare_query_params(**kwargs):
    
    return [
        (sub_key, sub_value)
        for key, value in kwargs.items()
        for sub_key, sub_value in expand(value, key)
        if sub_value is not None
    ]
715391
def _validate_param(rtype, fields):
    

    try:
        # raises ValueError if not found
        model = rtype_to_model(rtype)
        model_fields = model.all_fields
    except ValueError:
        raise InvalidQueryParams(**{
            'detail': 'The fields query param provided with a '
                      'field type of "%s" is unknown.' % rtype,
            'links': LINK,
            'parameter': PARAM,
        })

    for field in fields:
        if field not in model_fields:
            raise InvalidQueryParams(**{
                'detail': 'The fields query param "TYPE" of "%s" '
                          'is not possible. It does not have a field '
                          'by the name of "%s".' % (rtype, field),
                'links': LINK,
                'parameter': PARAM,
            })
705083
def init(req, model):
    

    rels = model.relationships
    fields = model.all_fields

    params = req.get_param_as_list('sort') or [goldman.config.SORT]
    params = [Sortable(param.lower()) for param in params]

    for param in params:
        _validate_no_rels(param, rels)
        _validate_field(param, fields)

    return params
206388
def _preprocess_params(cls, kwargs):
        
        # kwargs.pop('csrf_token', None)
        for attr, val in kwargs.items():
            if cls.is_the_primary_key(attr) and cls._prevent_primary_key_initialization_:
                del kwargs[attr]
                continue
            if val == "":
                # Making an assumption that there is no good usecase
                # for setting an empty string. This will help prevent
                # cases where empty string is sent because of client
                # not clearing form fields to null
                kwargs[attr] = None
                continue
            if attr in class_mapper(cls).relationships and attr not in cls._no_overwrite_:
                rel = class_mapper(cls).relationships[attr]
                if rel.uselist:
                    if isinstance(val, list):
                        if all(isinstance(v, dict) for v in val):
                            rel_cls = cls.mapped_rel_class(attr)
                            kwargs[attr] = rel_cls.update_or_new_all(
                                list_of_kwargs=val, keys=[rel_cls.primary_key_name()])
                    elif isinstance(val, dict):
                        rel_cls = cls.mapped_rel_class(attr)
                        mapping_col = rel.collection_class().keyfunc.name
                        list_of_kwargs = [merge(v, {mapping_col: k}) for k, v in val.items()]
                        kwargs[attr] = {getattr(obj, mapping_col): obj for obj in rel_cls.update_or_new_all(
                            list_of_kwargs=list_of_kwargs, keys=[rel_cls.primary_key_name()])}
                elif isinstance(val, dict):
                    rel_cls = cls.mapped_rel_class(attr)
                    kwargs[attr] = rel_cls.update_or_new(
                        **merge(val, {'keys': [rel_cls.primary_key_name()]}))
        return kwargs
1047514
def _set_properties(self, api_response):
        
        self._properties.clear()
        cleaned = api_response.copy()
        if "name" in cleaned:
            self.name = config_name_from_full_name(cleaned.pop("name"))
        self._properties.update(cleaned)
252978
def fixup_instance(sender, **kwargs):
    
    instance = kwargs['instance']
    for model_field in instance._meta.fields:

        if not isinstance(model_field, JSONAttributeField):
            continue

        if hasattr(instance, '_attr_field'):
            raise FieldError('multiple JSONAttributeField fields: '
                             'only one is allowed per model!')

        field_name = model_field.name
        attrs = getattr(instance, field_name)

        # ensure JSONAttributeField's data is of JSONAttributes type
        if not isinstance(attrs, JSONAttributes):
            setattr(instance, field_name, JSONAttributes(attrs))
            attrs = getattr(instance, field_name)

        # Cache model instance on JSONAttributes instance and vice-versa
        attrs._instance = instance
        attrs._get_from_instance = functools.partial(
            getattr, instance, field_name)
        instance._attr_field = attrs

    if not hasattr(instance, '_attr_field'):
        raise FieldError('missing JSONAttributeField field in '
                         'fixup_instance decorator')
1094254
def _match_setters(self, query):
        
        q = query.decode('utf-8')
        for name, parser, response, error_response in self._setters:
            try:
                value = parser(q)
                logger.debug('Found response in setter of %s' % name)
            except ValueError:
                continue

            try:
                self._properties[name].set_value(value)
                return response
            except ValueError:
                if isinstance(error_response, bytes):
                    return error_response
                return self.error_response('command_error')

        return None
283308
def setattr(self, key, value):
		
		if key in _MethodFactoryMeta[self.classId]:
			self.__dict__[key] = value
		elif key == 'errorCode':
			self.errorCode = value
		elif key == 'errorDescr':
			self.errorDescr = value
		elif key == 'invocationResult':
			self.invocationResult = value
		elif key == 'response':
			self.response = value
		else:
			""" no such property """
			# print "No such property ClassId: %s Property:%s" %(self.classId, key)
			return None
265805
def _from_dict(cls, _dict):
        """"""
        args = {}
        if 'environment_id' in _dict:
            args['environment_id'] = _dict.get('environment_id')
        if 'collection_id' in _dict:
            args['collection_id'] = _dict.get('collection_id')
        if 'queries' in _dict:
            args['queries'] = [
                TrainingQuery._from_dict(x) for x in (_dict.get('queries'))
            ]
        return cls(**args)
1263259
def set(self, obj, build_kwargs):
        """"""
        if build_kwargs is None:
            build_kwargs = {}

        cached = {}
        if 'queryset' in build_kwargs:
            cached = {
                'model': build_kwargs['queryset'].model,
                'pks': list(build_kwargs['queryset'].values_list('pk', flat=True)),
            }

        elif 'obj' in build_kwargs:
            cached = {
                'obj': build_kwargs['obj'],
            }

        if not hasattr(self._thread_local, 'cache'):
            self._thread_local.cache = {}
        self._thread_local.cache[self._get_cache_key(obj)] = cached
502914
def patch(self, fields, **args):
        
        self_dict = dict([(key, value) for (key, value) in
                          self.to_dict().items()
                          if key in fields])
        if args:
            self_dict = dict(list(self_dict.items()) + list(args.items()))
        response = self.requester.patch(
            '/{endpoint}/{id}', endpoint=self.endpoint,
            id=self.id, payload=self_dict
        )
        obj_json = response.json()
        if 'version' in obj_json:
            self.__dict__['version'] = obj_json['version']
        return self
805874
def set_attrs(self):
        
        self.attrs.encoding = self.encoding
        self.attrs.errors = self.errors
264995
def load_fields(self, *fields):
        ''''''
        if self._loadedfields is not None:
            if self.session is None:
                raise SessionNotAvailable('No session available')
            meta = self._meta
            kwargs = {meta.pkname(): self.pkvalue()}
            obj = session.query(self).load_only(fields).get(**kwargs)
            for name in fields:
                field = meta.dfields.get(name)
                if field is not None:
                    setattr(self, field.attname,
                            getattr(obj, field.attname, None))
901407
def _reset(self, **kwargs):
        
        # set object attributes from params
        for key in kwargs:
            setattr(self, key, kwargs[key])

        # set defaults (if need be) where the default is not None
        for attr in self.ATTRIBUTES:
            if not hasattr(self, attr) and self.ATTRIBUTES[attr] is not None:
                setattr(self, attr, self.ATTRIBUTES[attr])
1302493
def _process_settings(**kwargs):
    

    # If we are in this method due to a signal, only reload for our settings
    setting_name = kwargs.get('setting', None) 
    if setting_name is not None and setting_name != 'QUERYCOUNT':
        return

    # Support the old-style settings
    if getattr(settings, 'QUERYCOUNT_THRESHOLDS', False):
        QC_SETTINGS['THRESHOLDS'] = settings.QUERYCOUNT_THRESHOLDS

    # Apply new-style settings
    if not getattr(settings, 'QUERYCOUNT', False):
        return

    # Duplicate display is a special case, configure it specifically
    if 'DISPLAY_DUPLICATES' in settings.QUERYCOUNT:
        duplicate_settings = settings.QUERYCOUNT['DISPLAY_DUPLICATES']
        if duplicate_settings is not None:
            duplicate_settings = int(duplicate_settings)
        QC_SETTINGS['DISPLAY_DUPLICATES'] = duplicate_settings

    # Apply the rest of the setting overrides
    for key in ['THRESHOLDS',
                'IGNORE_REQUEST_PATTERNS',
                'IGNORE_SQL_PATTERNS',
                'IGNORE_PATTERNS',
                'RESPONSE_HEADER']:
        if key in settings.QUERYCOUNT:
            QC_SETTINGS[key] = settings.QUERYCOUNT[key]