Like get_object_or_404, but doesn't throw an exception.

    Allows querying for an object that might not exist without triggering
    an exception.
777321
def get_object_or_none(model, *args, **kwargs):
    
    try:
        return model._default_manager.get(*args, **kwargs)
    except model.DoesNotExist:
        return None
697327
def get_object_from_list_detail_view(request, *args, **kwargs):
    
    queryset = kwargs['queryset']
    object_id = kwargs.get('object_id', None)
    slug = kwargs.get('slug', None)
    slug_field = kwargs.get('slug_field', 'slug')
    if object_id:
        obj = get_object_or_404(queryset, pk=object_id)
    elif slug and slug_field:
        obj = get_object_or_404(queryset, **{slug_field: slug})
    else:
        raise AttributeError(
                "Generic detail view must be called with either an "
                "object_id or a slug/slug_field."
            )
    return obj
637892
def get_object_or_404(self, queryset, *filter_args, **filter_kwargs):
        
        if isinstance(queryset, CachedQueryset):
            try:
                return queryset.get(*filter_args, **filter_kwargs)
            except queryset.model.DoesNotExist:
                raise Http404(
                    'No %s matches the given query.' % queryset.model)
        else:
            return get_object_or_404(queryset, *filter_args, **filter_kwargs)
738534
def _get(self, version, method, url_or_urls, **kwargs):
        
        if not url_or_urls:
            raise ValueError('%s requires a url or a list of urls given: %s' %
                             (method.title(), url_or_urls))

        # a flag we can use instead of calling isinstance() all the time
        multi = isinstance(url_or_urls, list)

        # throw an error early for too many URLs
        if multi and len(url_or_urls) > 20:
            raise ValueError('Embedly accepts only 20 urls at a time. Url '
                             'Count:%s' % len(url_or_urls))

        query = ''

        key = kwargs.get('key', self.key)

        # make sure that a key was set on the client or passed in
        if not key:
            raise ValueError('Requires a key. None given: %s' % key)

        kwargs['key'] = key

        query += urlencode(kwargs)

        if multi:
            query += '&urls=%s&' % ','.join([quote(url) for url in url_or_urls])
        else:
            query += '&url=%s' % quote(url_or_urls)

        url = 'http://api.embed.ly/%s/%s?%s' % (version, method, query)

        http = httplib2.Http(timeout=self.timeout)

        headers = {'User-Agent': self.user_agent,
                   'Connection': 'close'}

        resp, content = http.request(url, headers=headers)

        if resp['status'] == '200':
            data = json.loads(content.decode('utf-8'))

            if kwargs.get('raw', False):
                data['raw'] = content
        else:
            data = {'type': 'error',
                    'error': True,
                    'error_code': int(resp['status'])}

        if multi:
            return map(lambda url, data: Url(data, method, url),
                       url_or_urls, data)

        return Url(data, method, url_or_urls)
652653
def object_url(self, object_t, object_id=None, relation=None, **kwargs):
        
        if object_t not in self.objects_types:
            raise TypeError("{} is not a valid type".format(object_t))
        request_items = (
            str(item) for item in [object_t, object_id, relation] if item is not None
        )
        request = "/".join(request_items)
        base_url = self.url(request)
        if self.access_token is not None:
            kwargs["access_token"] = str(self.access_token)
        if kwargs:
            for key, value in kwargs.items():
                if not isinstance(value, str):
                    kwargs[key] = str(value)
            # kwargs are sorted (for consistent tests between Python < 3.7 and >= 3.7)
            sorted_kwargs = SortedDict.from_dict(kwargs)
            result = "{}?{}".format(base_url, urlencode(sorted_kwargs))
        else:
            result = base_url
        return result
1274956
def get_url(self, obj, view_name, request, format):
        
        # Unsaved objects will not yet have a valid URL.
        if hasattr(obj, 'pk') and obj.pk is None:
            return None

        lookup_value = getattr(obj, self.lookup_field)
        kwargs = {self.lookup_url_kwarg: lookup_value}
        return self.reverse(view_name, kwargs=kwargs, request=request, format=format)
964952
def get_object(self):
        
        queryset = None
        slug = self.kwargs.get(self.slug_url_kwarg, None)

        if slug is not None:
            queryset = self.get_queryset()
            slug_field = self.slug_field
            queryset = queryset.filter(**{slug_field: slug})
            try:
                self.object = queryset.get()
            except ObjectDoesNotExist:
                raise http.Http404
        return self.object
348124
def get_object(self, *args, **kwargs):
        
        self.category_instance = get_object_or_404(Category, slug=self.kwargs['category_slug'])
        return get_object_or_404(Post, thread__id=self.kwargs['thread_id'], thread__category=self.category_instance, pk=self.kwargs['post_id'])
455102
def get_object_by_record(record):
    

    # nothing to do here
    if not record:
        return None

    if record.get("uid"):
        return get_object_by_uid(record["uid"])
    if record.get("path"):
        return get_object_by_path(record["path"])
    if record.get("parent_path") and record.get("id"):
        path = "/".join([record["parent_path"], record["id"]])
        return get_object_by_path(path)

    logger.warn("get_object_by_record::No object found! record='%r'" % record)
    return None
1316933
def get_object(self, queryset=None):
        
        obj = super(EntryPreviewMixin, self).get_object(queryset)
        if obj.is_visible:
            return obj
        if (self.request.user.has_perm('zinnia.can_view_all') or
                self.request.user.pk in [
                author.pk for author in obj.authors.all()]):
            return obj
        raise Http404(_('No entry found matching the query'))
1109257
def find_by(cls, **kwargs) -> 'Entity':
        
        logger.debug(f'Lookup `{cls.__name__}` object with values '
                     f'{kwargs}')

        # Find this item in the repository or raise Error
        results = cls.query.filter(**kwargs).limit(1).all()

        if not results:
            raise ObjectNotFoundError(
                f'`{cls.__name__}` object with values {[item for item in kwargs.items()]} '
                f'does not exist.')

        # Return the first result
        return results.first
95552
def get_or_404(self, ident, description=None):
        """"""

        rv = self.get(ident)
        if rv is None:
            abort(404, description=description)
        return rv
447863
def get_or_connect(cls, **kwargs):
        
        try:
            inst = cls.get(**kwargs)
            created = False
        except DoesNotExist:
            inst = cls(**kwargs)
            created = True
        except Exception:
            raise
        return inst, created
563703
def get_value(cls, object_version, key):
        """"""
        obj = cls.get(object_version, key)
        return obj.value if obj else None
1136226
def _object_client(self, *, not_found=None):
        """"""
        if self.gs_object_client is None:
            if self.gs is None:
                self.gs = self._init_google_client()
            self.gs_object_client = self.gs.objects()  # pylint: disable=no-member

        try:
            yield self.gs_object_client
        except HttpError as ex:
            if ex.resp["status"] == "404" and not_found is not None:
                raise FileNotFoundFromStorageError(not_found)
            if ex.resp["status"] >= "500" and ex.resp["status"] <= "599":
                self.log.error("Received server error %r, resetting Google API client", ex.resp["status"])
                self.gs = None
                self.gs_object_client = None
            raise
728526
def get_object(self, id, **args):
        """"""
        return self.request("{0}/{1}".format(self.version, id), args)
511284
def get_object_or_this(model, this=None, *args, **kwargs):
    

    return get_object_or_None(model, *args, **kwargs) or this