Retrieve an object through sqlalchemy

        :params dict view_kwargs: kwargs from the resource view
        :return DeclarativeMeta: an object from sqlalchemy
506110
def get_object(self, view_kwargs, qs=None):
        
        self.before_get_object(view_kwargs)

        id_field = getattr(self, 'id_field', inspect(self.model).primary_key[0].key)
        try:
            filter_field = getattr(self.model, id_field)
        except Exception:
            raise Exception("{} has no attribute {}".format(self.model.__name__, id_field))

        url_field = getattr(self, 'url_field', 'id')
        filter_value = view_kwargs[url_field]

        query = self.retrieve_object_query(view_kwargs, filter_field, filter_value)

        if qs is not None:
            query = self.eagerload_includes(query, qs)

        try:
            obj = query.one()
        except NoResultFound:
            obj = None

        self.after_get_object(obj, view_kwargs)

        return obj
85171
def get_object(self, **kwargs) ->Model:
        
        queryset = self.filter_queryset(
            queryset=self.get_queryset(**kwargs),
            **kwargs
        )

        # Perform the lookup filtering.
        lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field

        assert lookup_url_kwarg in kwargs, (
                'Expected view %s to be called with a URL keyword argument '
                'named "%s". Fix your URL conf, or set the `.lookup_field` '
                'attribute on the view correctly.' %
                (self.__class__.__name__, lookup_url_kwarg)
        )

        filter_kwargs = {self.lookup_field: kwargs[lookup_url_kwarg]}

        obj = get_object_or_404(queryset, **filter_kwargs)
        # TODO check_object_permissions

        return obj
1199054
def get_queryset(qs=None, app=DEFAULT_APP, db_alias=None):
    
    # app = get_app(app);
    # print 'get_model' + repr(model) + ' app ' + repr(app)
    if isinstance(qs, (djmodels.Manager, djmodels.query.QuerySet)):
        qs = qs.all()
    else:
        qs = get_model(qs, app=app).objects.all()
    if db_alias:
        return qs.using(db_alias)
    else:
        return qs
1283570
def get_view_model(cls):
    
    msg = 'When using get_queryset you must set a auto_filters_model field in the viewset'
    if cls.queryset is not None:
        return cls.queryset.model
    else:
        assert hasattr(cls, 'auto_filters_model'), msg
        return cls.auto_filters_model
1323615
def get_object_by_natural_key(self, app_label, model_name, object_id):
        
        try:
            model_type = ContentType.objects.get_by_natural_key(app_label, model_name)
        except ContentType.DoesNotExist:
            return None

        # Pointless to fetch the object, if there is no URL to generate
        # Avoid another database query.
        ModelClass = model_type.model_class()
        if not hasattr(ModelClass, 'get_absolute_url'):
            return None

        try:
            return model_type.get_object_for_this_type(pk=object_id)
        except ObjectDoesNotExist:
            return None
1201208
def view(self, *args, **kwargs):
        
        def decorator(f):
            kwargs.setdefault("view_class", self.view_class)
            return self.add_view(as_view(*args, **kwargs)(f))
        return decorator
1129608
def get_data_for_model(self, args, kwargs):
        
        kwargs_from_invocation = self.get_raw_data()
        args_from_invocation = deque(self.path_args)

        defaults = kwargs
        values = args + list(kwargs.keys())

        output = {}

        raw = False
        for i, field in enumerate(values):
            ## going through each bit of data that the model needs
            ## `field` here is the name of each needed var.

            # the 'default' value that may be defined in the model.
            # this variable might be a string or int or might even be a primitive object.
            # NotImplemented here is used as to preserve if a default value is None.
            # it is used here as a sort of MetaNone.
            default_defined_in_model = defaults.get(field, NotImplemented)
            
            # the value in kwarg arguments such as --values and GET params
            from_data_kwargs = kwargs_from_invocation.get(field, None)

            # The value that will end up being used.
            value_to_use = None

            if default_defined_in_model == RAW_INVOCATION_ARGS:
                # flag that the RAW_INVOCATION_ARGS primitive has been invoked
                # used later to suppress errors for unused program args
                # when this primitive is invoked, all positional args are invalid. 
                raw = True

            if type(default_defined_in_model) == GiottoPrimitive:
                value_to_use = self.get_primitive(default_defined_in_model.name)
            elif from_data_kwargs:
                value_to_use = from_data_kwargs
            elif not raw and args_from_invocation:
                value_to_use = args_from_invocation.popleft()
            elif default_defined_in_model is not NotImplemented:
                value_to_use = default_defined_in_model
            else:
                raise InvalidInvocation("Data Missing For Program. Missing: %s" % field)
            
            output[field] = value_to_use

        if args_from_invocation and not raw:
            msg = "Too many arguments. Program `%s` takes %s arguments, %s given" % (
                self.program.name, len(args) + len(kwargs), len(args_from_invocation)
            )
            raise InvalidInvocation(msg)

        return output
1153949
def as_view(cls, **initkwargs):
        
        # sanitize keyword arguments
        for key in initkwargs:
            if key in cls.http_method_names:
                raise TypeError("You tried to pass in the %s method name as a "
                                "keyword argument to %s(). Don't do that."
                                % (key, cls.__name__))
            if not hasattr(cls, key):
                raise TypeError("%s() received an invalid keyword %r. as_view "
                                "only accepts arguments that are already "
                                "attributes of the class." % (
                                    cls.__name__, key))

        def view(request, *args, **kwargs):
            self = cls(**initkwargs)
            if hasattr(self, 'get') and not hasattr(self, 'head'):
                self.head = self.get
            self.request = request
            self.args = args
            self.kwargs = kwargs
            self.authed_view = initkwargs.get('authed_view')
            self.authed_view_kwargs = initkwargs.get('authed_view_kwargs')
            self.anonymous_view = initkwargs.get('anonymous_view')
            self.anonymous_view_kwargs = initkwargs.get(
                'anonymous_view_kwargs')
            return self.dispatch(request, *args, **kwargs)
        # take name and docstring from class
        update_wrapper(view, cls, updated=())
        # and possible attributes set by decorators
        # like csrf_exempt from dispatch
        update_wrapper(view, cls.dispatch, assigned=())
        return view
1003677
def metadata(self):
        """"""

        from sqlalchemy import MetaData

        metadata = MetaData(bind=self.engine, schema=self._schema)

        metadata.reflect(self.engine)

        return metadata
941016
def view_call(method_name, *args, **kwargs):
    

    def view_call(_value, context, **_params):
        method = getattr(context["view"], method_name)
        return _call(method, args, kwargs)

    return view_call
923226
def get_detail_view(self, request, object, opts=None):
        
        view = self.get_view(request, self.view_class, opts)
        view.object = object
        return view
78635
def view_get(method_name):
    

    def view_get(_value, context, **_params):
        method = getattr(context["view"], method_name)
        return _get(method, context["key"], (), {})

    return view_get
1148574
def view_set(method_name):
    

    def view_set(value, context, **_params):
        method = getattr(context["view"], method_name)
        return _set(method, context["key"], value, (), {})

    return view_set
186702
def _get(cls, kwarg_name):
        
        param_classes = cls._discover_params()
        try:
            param_class = param_classes[kwarg_name]
        except KeyError:
            raise ValueError('invalid param keyword {}'.format(kwarg_name))
        else:
            return param_class
745038
def get_for_object(self, instance):
        
        # Return empty queryset if the given model instance is not a model instance.
        if not isinstance(instance, models.Model):
            return self.none()

        content_type = ContentType.objects.get_for_model(instance.__class__)
        pk = self._get_pk_value(instance)

        if isinstance(pk, integer_types):
            return self.filter(content_type=content_type, object_id=pk)
        else:
            return self.filter(content_type=content_type, object_pk=smart_text(pk))
226607
def get(self, *args, **kwargs):
        
        return self.session.get(*args, **self.get_kwargs(**kwargs))
357444
def as_view(cls, view_type, *init_args, **init_kwargs):
        
        global _method

        new_cls = type(
            cls.__name__ + '_' + _BridgeMixin.__name__ + '_restless',
            (_BridgeMixin, cls._request_handler_base_,),
            dict(
                __resource_cls__=cls,
                __resource_args__=init_args,
                __resource_kwargs__=init_kwargs,
                __resource_view_type__=view_type)
        )

        """
        Add required http-methods to the newly created class
        We need to scan through MRO to find what functions users declared,
        and then add corresponding http-methods used by Tornado.
        """
        bases = inspect.getmro(cls)
        bases = bases[0:bases.index(Resource)-1]
        for k, v in cls.http_methods[view_type].items():
            if any(v in base_cls.__dict__ for base_cls in bases):
                setattr(new_cls, k.lower(), _method)

        return new_cls