本文整理汇总了Python中rest_framework.generics.get_object_or_404方法的典型用法代码示例。如果您正苦于以下问题:Python generics.get_object_or_404方法的具体用法?Python generics.get_object_or_404怎么用?Python generics.get_object_or_404使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类rest_framework.generics
的用法示例。
在下文中一共展示了generics.get_object_or_404方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_object_with_lock
# 需要导入模块: from rest_framework import generics [as 别名]
# 或者: from rest_framework.generics import get_object_or_404 [as 别名]
def get_object_with_lock(self):
"""Return the object the view is displaying."""
queryset = self.filter_queryset(self.get_queryset())
# Perform the lookup filtering.
lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field
assert lookup_url_kwarg in self.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: self.kwargs[lookup_url_kwarg]}
# NOTE: The line below was changed.
obj = get_object_or_404(queryset.select_for_update(), **filter_kwargs)
# May raise a permission denied.
self.check_object_permissions(self.request, obj)
return obj
示例2: get_object
# 需要导入模块: from rest_framework import generics [as 别名]
# 或者: from rest_framework.generics import get_object_or_404 [as 别名]
def get_object(self):
"""Lookup a username by pk else use lookup_field"""
queryset = self.filter_queryset(self.get_queryset())
lookup = self.kwargs.get(self.lookup_field)
filter_kwargs = {self.lookup_field: lookup}
try:
pk = int(lookup)
except ValueError:
pass
else:
filter_kwargs = {'pk': pk}
obj = get_object_or_404(queryset, **filter_kwargs)
# May raise a permission denied
self.check_object_permissions(self.request, obj)
return obj
示例3: get_object
# 需要导入模块: from rest_framework import generics [as 别名]
# 或者: from rest_framework.generics import get_object_or_404 [as 别名]
def get_object(self):
"""Lookup user profile by pk or username"""
lookup = self.kwargs.get(self.lookup_field, None)
if lookup is None:
raise ParseError(
'Expected URL keyword argument `%s`.' % self.lookup_field
)
queryset = self.filter_queryset(self.get_queryset())
try:
pk = int(lookup)
except (TypeError, ValueError):
filter_kwargs = {'username': lookup}
else:
filter_kwargs = {'pk': pk}
# Return a 404 if the user does not exist
user = get_object_or_404(User, **filter_kwargs)
# Since the user does exist, create a matching profile if necessary
obj, created = queryset.get_or_create(user=user)
# May raise a permission denied
self.check_object_permissions(self.request, obj)
return obj
示例4: reactions
# 需要导入模块: from rest_framework import generics [as 别名]
# 或者: from rest_framework.generics import get_object_or_404 [as 别名]
def reactions(self, request, pk):
"""route for POST /messages/{id}/reactions/ with body {"name":"emoji_name"}"""
message = get_object_or_404(ConversationMessage, id=pk)
self.check_object_permissions(self.request, message)
data = {
'message': pk,
'name': request.data.get('name'),
'user': request.user.id,
}
serializer = ConversationMessageReactionSerializer(data=data)
serializer.is_valid(raise_exception=True)
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
示例5: token
# 需要导入模块: from rest_framework import generics [as 别名]
# 或者: from rest_framework.generics import get_object_or_404 [as 别名]
def token(self, *arg, **kwargs):
"""
Download the token belonging to a restricted mail. This token has to be attached to
the restricted mail for authentication.
"""
instance = get_object_or_404(RestrictedMail.objects.all(), id=kwargs["pk"])
auth = self.request.GET.get("auth")
if not instance.token_verify_query_param(auth):
raise exceptions.AuthenticationFailed
if not instance.token:
raise exceptions.NotFound
file_content = f"{RESTRICTED_TOKEN_PREFIX}{instance.token}"
response = HttpResponse(file_content)
response["Content-Disposition"] = 'attachment; filename="token"'
return response
示例6: get_object
# 需要导入模块: from rest_framework import generics [as 别名]
# 或者: from rest_framework.generics import get_object_or_404 [as 别名]
def get_object(self, queryset=None):
"""
Return the object the view is displaying.
Same as rest_framework.generics.GenericAPIView, but:
- Failed assertions instead of deprecations
"""
# Determine the base queryset to use.
assert queryset is None, "Passing a queryset is disabled"
queryset = self.filter_queryset(self.get_queryset())
# Perform the lookup filtering.
lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field
lookup = self.kwargs.get(lookup_url_kwarg, None)
assert lookup is not None, "Other lookup methods are disabled"
filter_kwargs = {self.lookup_field: lookup}
obj = self.get_object_or_404(queryset, **filter_kwargs)
# May raise a permission denied
self.check_object_permissions(self.request, obj)
return obj
示例7: get_object
# 需要导入模块: from rest_framework import generics [as 别名]
# 或者: from rest_framework.generics import get_object_or_404 [as 别名]
def get_object(self):
queryset = Group.objects.all()
lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field
assert lookup_url_kwarg in self.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: self.kwargs[lookup_url_kwarg]}
obj = get_object_or_404(queryset, **filter_kwargs)
# May raise a permission denied
self.check_object_permissions(self.request, obj)
return obj
示例8: post
# 需要导入模块: from rest_framework import generics [as 别名]
# 或者: from rest_framework.generics import get_object_or_404 [as 别名]
def post(self, request, prompt_uuid):
prompt = get_object_or_404(WriteUpPrompt, uuid=prompt_uuid)
user = request.user
serializer = WriteUpPromptVoteModifySerializer(data=request.data)
serializer.is_valid(raise_exception=True)
validated_data = serializer.validated_data
instance, created = WriteUpPromptVote.objects.update_or_create(
user=user, prompt=prompt, defaults=validated_data
)
# Temporary hack, switch to a denormalized process that should
# check and update this every five minutes instead
prompt = instance.prompt
prompt.score += 1
prompt.save()
return_serializer = WriteUpPromptVoteModifySerializer(instance=instance)
return Response(data=return_serializer.data)
示例9: get_queryset
# 需要导入模块: from rest_framework import generics [as 别名]
# 或者: from rest_framework.generics import get_object_or_404 [as 别名]
def get_queryset(self):
customer_pk = self.kwargs.get('customer_pk', None)
payment_method_id = self.kwargs.get('payment_method_id')
if payment_method_id:
payment_method = get_object_or_404(PaymentMethod,
id=payment_method_id,
customer__pk=customer_pk)
return Transaction.objects.filter(
payment_method=payment_method
)
else:
return Transaction.objects.filter(
payment_method__customer__pk=customer_pk
)
示例10: post
# 需要导入模块: from rest_framework import generics [as 别名]
# 或者: from rest_framework.generics import get_object_or_404 [as 别名]
def post(self, request, *args, **kwargs):
sub = get_object_or_404(Subscription,
pk=kwargs.get('subscription_pk', None))
if sub.state != Subscription.STATES.CANCELED:
msg = 'Cannot reactivate subscription from %s state.' % sub.state
return Response({"error": msg},
status=status.HTTP_400_BAD_REQUEST)
else:
sub.activate()
sub.save()
logger.debug('Reactivated subscription: %s', {
'subscription': sub.id,
'date': timezone.now().date().strftime('%Y-%m-%d'),
})
return Response({"state": sub.state},
status=status.HTTP_200_OK)
示例11: get
# 需要导入模块: from rest_framework import generics [as 别名]
# 或者: from rest_framework.generics import get_object_or_404 [as 别名]
def get(self, request, format=None, **kwargs):
subscription_pk = kwargs.get('subscription_pk', None)
mf_product_code = kwargs.get('mf_product_code', None)
subscription = Subscription.objects.get(pk=subscription_pk)
metered_feature = get_object_or_404(
subscription.plan.metered_features,
product_code__value=mf_product_code
)
logs = MeteredFeatureUnitsLog.objects.filter(
metered_feature=metered_feature.pk,
subscription=subscription_pk)
serializer = MFUnitsLogSerializer(
logs, many=True, context={'request': request}
)
return Response(serializer.data)
示例12: put
# 需要导入模块: from rest_framework import generics [as 别名]
# 或者: from rest_framework.generics import get_object_or_404 [as 别名]
def put(self, request, *args, **kwargs):
doc_pk = kwargs.get('document_pk')
entry_pk = kwargs.get('entry_pk')
Model = self.get_model()
model_name = self.get_model_name()
document = get_object_or_404(Model, pk=doc_pk)
if document.state != BillingDocumentBase.STATES.DRAFT:
msg = "{model} entries can be added only when the {model_lower} is"\
" in draft state.".format(model=model_name,
model_lower=model_name.lower())
return Response({"detail": msg}, status=status.HTTP_403_FORBIDDEN)
searched_fields = {model_name.lower(): document, 'pk': entry_pk}
entry = get_object_or_404(DocumentEntry, **searched_fields)
serializer = DocumentEntrySerializer(entry, data=request.data,
context={'request': request})
if serializer.is_valid(raise_exception=True):
serializer.save()
return Response(serializer.data)
示例13: delete
# 需要导入模块: from rest_framework import generics [as 别名]
# 或者: from rest_framework.generics import get_object_or_404 [as 别名]
def delete(self, request, *args, **kwargs):
doc_pk = kwargs.get('document_pk')
entry_pk = kwargs.get('entry_pk')
Model = self.get_model()
model_name = self.get_model_name()
document = get_object_or_404(Model, pk=doc_pk)
if document.state != BillingDocumentBase.STATES.DRAFT:
msg = "{model} entries can be deleted only when the {model_lower} is"\
" in draft state.".format(model=model_name,
model_lower=model_name.lower())
return Response({"detail": msg}, status=status.HTTP_403_FORBIDDEN)
searched_fields = {model_name.lower(): document, 'pk': entry_pk}
entry = get_object_or_404(DocumentEntry, **searched_fields)
entry.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
示例14: put
# 需要导入模块: from rest_framework import generics [as 别名]
# 或者: from rest_framework.generics import get_object_or_404 [as 别名]
def put(self, request, *args, **kwargs):
data = request.data
user = request.user
try:
uuid = data['uuid']
except KeyError:
raise Http404
instance = get_object_or_404(self.model, user=user, uuid=uuid)
serializer = self.update_serializer_class(instance, data=request.data, partial=True)
if serializer.is_valid():
serializer.save()
else:
return Response('Invalid Data Submitted {}'.format(data), status=400)
return Response(serializer.data)
示例15: _get_analytics_dataframe
# 需要导入模块: from rest_framework import generics [as 别名]
# 或者: from rest_framework.generics import get_object_or_404 [as 别名]
def _get_analytics_dataframe(cls, user, supplement_uuid):
supplement = get_object_or_404(Supplement, uuid=supplement_uuid, user=user)
supplement_series = cls._get_daily_supplement_events_series_last_year(user, supplement)
sleep_series = cls._get_sleep_series_last_year(user)
productivity_series = cls._get_productivity_series_last_year(user)
# if either sleep or productivity are empty, create an empty series that is timezone
# aware (hence, matching the supplement index)
if sleep_series.empty:
sleep_series = pd.Series(index=supplement_series.index)
if productivity_series.empty:
productivity_series = pd.Series(index=supplement_series.index)
dataframe_details = {
'supplement': supplement_series,
'sleep': sleep_series,
'productivity': productivity_series
}
dataframe = pd.DataFrame(dataframe_details)
return dataframe