def webfinger_view(request):
"""Generate a webfinger document."""
q = request.GET.get("q")
if not q:
raise Http404()
username = q.split("@")[0]
if username.startswith("acct:"):
username = username.replace("acct:", "", 1)
user = get_object_or_404(User, username=username)
# Create webfinger document
webfinger = generate_legacy_webfinger(
"diaspora",
handle="{username}@{domain}".format(username=user.username, domain=settings.SOCIALHOME_DOMAIN),
host=settings.SOCIALHOME_URL,
guid=str(user.profile.guid),
public_key=user.profile.rsa_public_key
)
return HttpResponse(webfinger, content_type="application/xrd+xml")
python类Http404()的实例源码
def hcard_view(request, guid):
"""Generate a hcard document.
For local users only.
"""
try:
profile = get_object_or_404(Profile, guid=guid, user__isnull=False)
except ValueError:
raise Http404()
hcard = generate_hcard(
"diaspora",
hostname=settings.SOCIALHOME_URL,
fullname=profile.name,
firstname=profile.get_first_name(),
lastname=profile.get_last_name(),
photo300=profile.safer_image_url_large,
photo100=profile.safer_image_url_medium,
photo50=profile.safer_image_url_small,
searchable="true" if profile.public else "false",
guid=profile.guid,
username=profile.user.username,
public_key=profile.rsa_public_key,
)
return HttpResponse(hcard)
def initial(self, request, *args, **kwargs):
"""
Find parent if any
"""
node_id = self.request.QUERY_PARAMS.get('node')
parent_id = self.request.QUERY_PARAMS.get('parent_node')
if node_id and node_id.isdigit():
try:
node = Node.objects.get(id=node_id)
except Node.DoesNotExist:
raise Http404("Parent node was not found.")
else:
self.kwargs['node'] = node
elif parent_id and parent_id.isdigit():
try:
node = Node.objects.get(id=parent_id)
except Node.DoesNotExist:
raise Http404("Parent node was not found.")
else:
self.kwargs['parent_node'] = node
else:
detail = "node or node_parent query parameter is missing"
raise CustomAPIException(status_code=400, detail=detail)
return super(PolicyViewSet, self).initial(request, *args, **kwargs)
def finish_reservation(request):
if not hasattr(request, 'reservation'):
raise Http404(_("No reservation object started"))
if request.method == "GET":
response = render(
request,
'djreservation/reservation_confirm.html',
{"reservation": request.reservation})
elif request.method == "POST":
reservation = request.reservation
reservation.status = reservation.REQUESTED
reservation.save()
request.reservation = None
send_reservation_email(reservation, request.user)
response = render(
request, 'djreservation/reservation_finished.html')
response.set_cookie("reservation", "0")
messages.success(request, _('Reservation finised'))
return response
def update_reservation_by_token(request, pk, token, status):
token_reservation = get_object_or_404(ReservationToken, reservation=pk,
token=token)
status_available = list(dict(Reservation.STATUS).keys())
if int(status) not in status_available:
raise Http404()
reservation = token_reservation.reservation
if int(status) == Reservation.ACCEPTED:
reservation.product_set.all().update(borrowed=True)
reservation.status = status
reservation.save()
token_reservation.delete()
messages.success(request, _('Reservation updated successful'))
return redirect("/")
def get_object(self, queryset=None):
"""
Returns the object the view is displaying.
By default this requires `self.queryset` and a `pk` or `slug` argument
in the URLconf, but subclasses can override this to return any object.
"""
obj = super(SingleObjectMixin, self).get_object(queryset=queryset)
# TODO: Consider if we want to support normal pk/slug stuff...
if not obj:
raise Http404(_("No %(verbose_name)s found matching the query") %
{'verbose_name': self.model._meta.verbose_name})
return obj
def endpoint(self, request, *args, **kwargs):
try:
return super(PageView, self).endpoint(request, *args, **kwargs)
except ApiException as e:
if e.error_code == ERROR_CODES.PARAMS:
if self.signature_salt:
return redirect('/error/invalid_signature/')
raise Http404()
if e.error_code == ERROR_CODES.SIGNATURE:
return redirect('/error/invalid_signature/')
if e.error_code == ERROR_CODES.EXPIRED_SIGNATURE:
return redirect('/error/expired_link/')
if e.status_code != 404:
return HttpResponse(e.message, status=e.status_code)
if e.error_code != ERROR_CODES.PERMISSION:
raise Http404()
path = request.get_full_path()
return redirect_to_login(path, settings.LOGIN_URL, 'next')
def content_fetch_view(request, objtype, guid):
"""Diaspora content fetch view.
Returns the signed payload for the public content. Non-public content will return 404.
If the content is not local, redirect to content author server.
Args:
objtype (str) - Diaspora content type. Currently if it is `status_message`, `post` or `reshare`,
we try to find `Content`.
guid (str) - The object guid to look for.
"""
if objtype not in ["status_message", "post", "reshare", "comment"]:
raise Http404()
content = get_object_or_404(Content, guid=guid, visibility=Visibility.PUBLIC)
if not content.local:
url = "https://%s/fetch/%s/%s" % (
content.author.handle.split("@")[1], objtype, guid
)
return HttpResponseRedirect(url)
entity = make_federable_content(content)
message = get_full_xml_representation(entity, content.author.private_key)
document = MagicEnvelope(
message=message, private_key=content.author.private_key, author_handle=content.author.handle
)
return HttpResponse(document.render(), content_type="application/magic-envelope+xml")
def get(self, request, *args, **kwargs):
try:
return super(ResultView, self).get(request, *args, **kwargs)
except Http404:
messages.add_message(self.request, messages.WARNING,
_('Check result does not exist (anymore)'))
return HttpResponseRedirect(redirect_to=reverse_lazy(
'django_datawatch_index'))
def test_not_live(self):
"""
Purchasable course runs must be live
"""
course_run, user = create_purchasable_course_run()
program = course_run.course.program
program.live = False
program.save()
with self.assertRaises(Http404):
get_purchasable_course_run(course_run.edx_course_key, user)
def test_financial_aid_not_available(self):
"""
Purchasable course runs must have financial aid available
"""
course_run, user = create_purchasable_course_run()
program = course_run.course.program
program.financial_aid_availability = False
program.save()
with self.assertRaises(Http404):
get_purchasable_course_run(course_run.edx_course_key, user)
def test_no_program_enrollment(self):
"""
For a user to purchase a course run they must already be enrolled in the program
"""
course_run, user = create_purchasable_course_run()
ProgramEnrollment.objects.filter(program=course_run.course.program, user=user).delete()
with self.assertRaises(Http404):
create_unfulfilled_order(course_run.edx_course_key, user)
def test_no_program_enrollment(self):
"""
If a user is not enrolled a 404 should be raised when getting the price
"""
course_run, user = create_purchasable_course_run()
ProgramEnrollment.objects.filter(program=course_run.course.program, user=user).delete()
with self.assertRaises(Http404):
calculate_run_price(course_run, user)
def test_response_404(self):
"It should raise 404 if there's no PublicationSeries with that slug."
with self.assertRaises(Http404):
response = views.PublicationSeriesDetailView.as_view()(
self.request, slug='nope')
def test_non_numeric_page(self):
"PaginatedListView should raise 404 if we ask for a non-numeric page that isn't 'last'."
request = self.factory.get('/fake-path/?p=asdf')
with self.assertRaises(Http404):
response = views.PublicationListView.as_view()(request)
def test_invalid_page(self):
"PaginatedListView should raise 404 if we ask for a page number that doesn't exist."
# Use a URL with p=99:
request = self.factory.get('/fake-path/?p=99')
with self.assertRaises(Http404):
response = views.PublicationListView.as_view()(request)
def test_response_404(self):
"It should raise 404 if there's no Publication with that slug."
with self.assertRaises(Http404):
response = views.PublicationDetailView.as_view()(self.request, slug='nope')
def test_response_404(self):
"It should raise 404 if it's a date before our first year."
with self.assertRaises(Http404):
response = views.ReadingYearArchiveView.as_view()(
self.request, year='2016')
def test_response_404(self):
"It should respond with 404 with an invalid kind_slug."
with self.assertRaises(Http404):
response = views.EventListView.as_view()(
self.request, kind_slug='nope')
def test_response_404_kind_slug(self):
"It should raise 404 if there's no Event with that kind_slug."
with self.assertRaises(Http404):
response = views.EventDetailView.as_view()(
self.request, kind_slug='nope', slug='my-gig')
def test_response_404_pk(self):
"It should raise 404 if there's no Event with that slug."
with self.assertRaises(Http404):
response = views.EventDetailView.as_view()(
self.request, kind_slug='gigs', slug='nope')
def test_response_404(self):
"It should raise 404 if there's no Movie with that slug."
with self.assertRaises(Http404):
response = views.EventDetailView.as_view()(
self.request, kind_slug='movies', slug='nope')
def test_response_404(self):
"It should raise 404 if there's no Play with that slug."
with self.assertRaises(Http404):
response = views.EventDetailView.as_view()(
self.request, kind_slug='plays', slug='nope')
def test_response_404(self):
"It should respond with 404."
with self.assertRaises(Http404):
response = views.ClassicalWorkDetailView.as_view()(
self.request, slug='nope')
def test_response_404(self):
"It should respond with 404."
with self.assertRaises(Http404):
response = views.DancePieceDetailView.as_view()(self.request, slug='nope')
def test_response_404(self):
"It should raise 404 if there's no Venue with that slug."
with self.assertRaises(Http404):
response = views.VenueDetailView.as_view()(self.request, slug='nope')
def get_object_or_404(klass, *args, **kwargs):
"""
Similar to django.shortcuts.get_object_or_404 but it also supports klass argument to be of type
restframework.Model or PartiallyFiltered
"""
if isinstance(klass, (ModelBase, PartiallyFiltered)):
partially_filtered = klass if isinstance(klass, PartiallyFiltered) else klass.objects.all()
model = partially_filtered.model
try:
return partially_filtered.get(*args, **kwargs)
except model.DoesNotExist:
raise Http404('No %s matches the given query.' % model._meta.object_name)
else:
return django_get_object_or_404(klass, *args, **kwargs)
test_restframeworkclient.py 文件源码
项目:django-rest-framework-client
作者: qvantel
项目源码
文件源码
阅读 16
收藏 0
点赞 0
评论 0
def test_get_object_or_404_raises_404_on_DoesNotExist(self, rest_call_mock):
rest_call_mock.side_effect = Customer.DoesNotExist
with self.assertRaises(Http404):
restframeworkclient.get_object_or_404(Customer, param='value')
def detail(request, question_id):
question = get_object_or_404(Question, pk=question_id)
# try:
# question = Question.objects.get(pk=question_id)
# except Question.DoesNotExist:
# raise Http404("Question does not exists.")
return render(request, 'polls/detail.html',{'question':question})
#return HttpResponse("You're looking at question %s." % question_id)
def post(self, request):
try:
code = request.data['code']
except KeyError:
return redirect('/500')
callback_uri = request.build_absolute_uri(reverse('fitbit-complete'))
fb = utils.create_fitbit(callback_uri=callback_uri)
try:
token = fb.client.fetch_access_token(code, callback_uri)
access_token = token['access_token']
fitbit_user_id = token['user_id']
except KeyError:
raise Http404('Invalid Token')
user = request.user
UserFitbit.objects.update_or_create(user=user, defaults={
'fitbit_user_id': fitbit_user_id,
'access_token': access_token,
'refresh_token': token['refresh_token'],
'expires_at': token['expires_at'],
})
next_url = request.session.pop('fitbit_next', None) or utils.get_setting('FITBIT_LOGIN_REDIRECT')
response = {'next_url': next_url}
return Response(response)