本文整理匯總了Python中django.http.HttpRequest方法的典型用法代碼示例。如果您正苦於以下問題:Python http.HttpRequest方法的具體用法?Python http.HttpRequest怎麽用?Python http.HttpRequest使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類django.http
的用法示例。
在下文中一共展示了http.HttpRequest方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: _create_view
# 需要導入模塊: from django import http [as 別名]
# 或者: from django.http import HttpRequest [as 別名]
def _create_view(self):
"""
Creates DjangoRestFramework view
:return: view
"""
view = self.callback()
view.kwargs = getattr(view, 'kwargs', dict())
if hasattr(self.introspector.pattern, 'default_args'):
view.kwargs.update(self.introspector.pattern.default_args)
view.request = HttpRequest()
view.request.user = AnonymousUser()
view.request.method = self.method
return view
示例2: test_default_serializer
# 需要導入模塊: from django import http [as 別名]
# 或者: from django.http import HttpRequest [as 別名]
def test_default_serializer(self):
if StrictVersion(VERSION) >= StrictVersion('3.0.0'):
return
from rest_framework.viewsets import ModelViewSet
from django.http import HttpRequest
from testapp.models import TestModel
class TestViewSet(ModelViewSet):
model = TestModel
view = TestViewSet()
view.request = HttpRequest()
si = SerializerIntrospector(view.get_serializer_class())
self.assertEqual(si.name, 'TestModelSerializer')
示例3: index
# 需要導入模塊: from django import http [as 別名]
# 或者: from django.http import HttpRequest [as 別名]
def index(request: HttpRequest, course_slug: str, activity_slug: str) -> HttpResponse:
role = request.member.role
offering = get_object_or_404(CourseOffering, slug=course_slug)
activity = get_object_or_404(Activity, slug=activity_slug, offering=offering, group=False)
if role in ['INST', 'TA']:
quiz = Quiz.objects.filter(activity=activity).first() # will be None if no quiz created for this activity
if not quiz:
# no quiz created? Only option is to create.
return redirect('offering:quiz:edit', course_slug=course_slug, activity_slug=activity_slug)
return _index_instructor(request, offering, activity, quiz)
elif role == 'STUD':
quiz = get_object_or_404(Quiz, activity=activity) # will 404 if no quiz created for this activity
return _index_student(request, offering, activity, quiz)
else:
raise Http404()
示例4: instructions
# 需要導入模塊: from django import http [as 別名]
# 或者: from django.http import HttpRequest [as 別名]
def instructions(request: HttpRequest, course_slug: str, activity_slug: str) -> HttpResponse:
offering = get_object_or_404(CourseOffering, slug=course_slug)
activity = get_object_or_404(Activity, slug=activity_slug, offering=offering, group=False)
quiz = get_object_or_404(Quiz, activity=activity)
start, end = quiz.get_start_end(member=request.member)
now = datetime.datetime.now()
if now > end:
return ForbiddenResponse(request, 'quiz is completed.')
context = {
'offering': offering,
'activity': activity,
'quiz': quiz,
'is_staff': request.member.role in ['INST', 'TA'],
'start': start,
'end': end,
}
return render(request, 'quizzes/instructions.html', context=context)
示例5: question_add
# 需要導入模塊: from django import http [as 別名]
# 或者: from django.http import HttpRequest [as 別名]
def question_add(request: HttpRequest, course_slug: str, activity_slug: str) -> HttpResponse:
offering = get_object_or_404(CourseOffering, slug=course_slug)
activity = get_object_or_404(Activity, slug=activity_slug, offering=offering, group=False)
quiz = get_object_or_404(Quiz, activity=activity)
if quiz.completed():
return ForbiddenResponse(request, 'quiz is completed. You cannot edit questions after the end of the quiz time')
if request.method == 'GET' and 'type' not in request.GET:
# ask for type of question
context = {
'offering': offering,
'activity': activity,
'quiz': quiz,
'question_type_choices': QUESTION_TYPE_CHOICES,
}
return render(request, 'quizzes/question_type.html', context=context)
return _question_edit(request, offering, activity, quiz, question=None, version=None)
示例6: version_delete
# 需要導入模塊: from django import http [as 別名]
# 或者: from django.http import HttpRequest [as 別名]
def version_delete(request: HttpRequest, course_slug: str, activity_slug: str, question_id: str, version_id: str) -> HttpResponse:
if request.method in ['POST', 'DELETE']:
quiz = get_object_or_404(Quiz, activity__slug=activity_slug, activity__offering__slug=course_slug)
if quiz.completed():
return ForbiddenResponse(request, 'Quiz is completed. You cannot modify questions after the end of the quiz time')
question = get_object_or_404(Question, quiz=quiz, id=question_id)
version = get_object_or_404(QuestionVersion, question=question, id=version_id)
other_versions = QuestionVersion.objects.filter(question=question).exclude(id=version_id)
if not other_versions.exists():
messages.add_message(request, messages.ERROR, 'Cannot delete the only version of a question.')
return redirect('offering:quiz:question_edit', course_slug=course_slug, activity_slug=activity_slug, question_id=question_id, version_id=version_id)
version.status = 'D'
version.save()
messages.add_message(request, messages.SUCCESS, 'Question version deleted.')
LogEntry(userid=request.user.username, description='deleted quiz question version id=%i' % (question.id,),
related_object=question).save()
return redirect('offering:quiz:index', course_slug=course_slug, activity_slug=activity_slug)
else:
return HttpError(request, status=405, title="Method Not Allowed", error='POST or DELETE requests only.')
示例7: submissions
# 需要導入模塊: from django import http [as 別名]
# 或者: from django.http import HttpRequest [as 別名]
def submissions(request: HttpRequest, course_slug: str, activity_slug: str) -> HttpResponse:
offering = get_object_or_404(CourseOffering, slug=course_slug)
activity = get_object_or_404(Activity, slug=activity_slug, offering=offering, group=False)
quiz = get_object_or_404(Quiz, activity=activity)
questions = Question.objects.filter(quiz=quiz)
answers = QuestionAnswer.objects.filter(question__in=questions) \
.select_related('student__person') \
.order_by('student__person')
students = set(a.student for a in answers)
starts_ends = quiz.get_starts_ends(students)
by_student = itertools.groupby(answers, key=lambda a: a.student)
subs_late = [(member, max(a.modified_at for a in ans) - starts_ends[member][1]) for member, ans in by_student]
context = {
'offering': offering,
'activity': activity,
'quiz': quiz,
'subs_late': subs_late,
'timedelta_zero': datetime.timedelta(seconds=0)
}
return render(request, 'quizzes/submissions.html', context=context)
示例8: _setup_download
# 需要導入模塊: from django import http [as 別名]
# 或者: from django.http import HttpRequest [as 別名]
def _setup_download(request: HttpRequest, course_slug: str, activity_slug: str):
offering = get_object_or_404(CourseOffering, slug=course_slug)
activity = get_object_or_404(Activity, slug=activity_slug, offering=offering, group=False)
quiz = get_object_or_404(Quiz, activity=activity)
questions = Question.objects.filter(quiz=quiz)
versions = QuestionVersion.objects.filter(question__in=questions)
version_number_lookup = { # version_number_lookup[question_id][version_id] == version_number
q_id: {v.id: i+1 for i,v in enumerate(vs)}
for q_id, vs in itertools.groupby(versions, key=lambda v: v.question_id)
}
answers = QuestionAnswer.objects.filter(question__in=questions) \
.select_related('student__person', 'question_version', 'question') \
.order_by('student__person')
by_student = itertools.groupby(answers, key=lambda a: a.student)
multiple_versions = len(questions) != len(versions)
return activity, questions, version_number_lookup, by_student, multiple_versions
示例9: submitted_file
# 需要導入模塊: from django import http [as 別名]
# 或者: from django.http import HttpRequest [as 別名]
def submitted_file(request: HttpRequest, course_slug: str, activity_slug: str, userid: str, answer_id: str, secret: str) -> StreamingHttpResponse:
offering = get_object_or_404(CourseOffering, slug=course_slug)
activity = get_object_or_404(Activity, slug=activity_slug, offering=offering, group=False)
member = get_object_or_404(Member, ~Q(role='DROP'), find_member(userid), offering__slug=course_slug)
answer = get_object_or_404(QuestionAnswer, question__quiz__activity=activity, student=member, id=answer_id)
real_secret = answer.answer['data'].get('secret', '?')
if real_secret != '?' and secret == real_secret:
return _return_submitted_file(answer.answer['data'], answer.file.open('rb'))
else:
# It's not the current submission, but an instructor looking at history might be trying to find an old one...
submissions = QuizSubmission.objects.filter(quiz__activity=activity, student=member)
for qs in submissions:
for answer_config in qs.config['answers']:
version_id, answer_id, a = answer_config
if not isinstance(a['data'], dict):
continue
real_secret = a['data'].get('secret', '?')
if answer.question_version_id == version_id and answer.id == answer_id and real_secret != '?' and secret == real_secret:
# aha! Temporarily replace answer.file with the old version (without saving) so we can return it
answer.file = a['filepath']
return _return_submitted_file(a['data'], answer.file.open('rb'))
raise Http404()
示例10: submission_history
# 需要導入模塊: from django import http [as 別名]
# 或者: from django.http import HttpRequest [as 別名]
def submission_history(request: HttpRequest, course_slug: str, activity_slug: str, userid: str) -> HttpResponse:
offering = get_object_or_404(CourseOffering, slug=course_slug)
activity = get_object_or_404(Activity, slug=activity_slug, offering=offering, group=False)
quiz = get_object_or_404(Quiz, activity=activity)
questions = Question.objects.filter(quiz=quiz)
versions = QuestionVersion.objects.filter(question__in=questions)
member = get_object_or_404(Member, ~Q(role='DROP'), find_member(userid), offering__slug=course_slug)
quiz_submissions = QuizSubmission.objects.filter(quiz=quiz, student=member)
[qs.annotate_questions(questions, versions) for qs in quiz_submissions]
context = {
'offering': offering,
'activity': activity,
'quiz': quiz,
'member': member,
'quiz_submissions': quiz_submissions,
'can_photo': has_photo_agreement(request.member.person)
}
return render(request, 'quizzes/submission_history.html', context=context)
示例11: test_master_list_pagination
# 需要導入模塊: from django import http [as 別名]
# 或者: from django.http import HttpRequest [as 別名]
def test_master_list_pagination(self):
request = http.HttpRequest()
first_part = common.Paginated(items=self.databases.list()[:1],
next_marker='marker')
second_part = common.Paginated(items=self.databases.list()[1:])
self.mock_instance_list.side_effect = [
first_part, second_part, first_part]
advanced_page = create_instance.AdvancedAction(request, None)
choices = advanced_page.populate_master_choices(request, None)
expected_calls = [
mock.call(request),
mock.call(request, marker='marker'),
mock.call(request)]
self.assertEqual(expected_calls,
self.mock_instance_list.call_args_list)
self.assertTrue(len(choices) == len(self.databases.list()) + 1)
示例12: test_user_owns_provisional
# 需要導入模塊: from django import http [as 別名]
# 或者: from django.http import HttpRequest [as 別名]
def test_user_owns_provisional(self):
"""
Tests that a user is the owner of a provisional edit
"""
json = {
"resourceinstance_id": "40000000-0000-0000-0000-000000000000",
"parenttile_id": "",
"nodegroup_id": "72048cb3-adbc-11e6-9ccf-14109fd34195",
"tileid": "",
"data": {"72048cb3-adbc-11e6-9ccf-14109fd34195": "TEST 1"},
}
user = User.objects.create_user(username="testuser", password="TestingTesting123!")
provisional_tile = Tile(json)
request = HttpRequest()
request.user = user
provisional_tile.save(index=False, request=request)
self.assertEqual(provisional_tile.user_owns_provisional(user), True)
示例13: scan_scan_list
# 需要導入模塊: from django import http [as 別名]
# 或者: from django.http import HttpRequest [as 別名]
def scan_scan_list(request: HttpRequest, scan_list_id: int) -> HttpResponse:
"""Schedule the scan of a scan list."""
scan_list = get_object_or_404(
ScanList.objects.prefetch_related(Prefetch(
'sites',
queryset=Site.objects.select_related('last_scan') \
.annotate_most_recent_scan_start() \
.annotate_most_recent_scan_end_or_null())
), pk=scan_list_id)
was_any_site_scannable = scan_list.scan()
if was_any_site_scannable:
num_scanning_sites = Scan.objects.filter(end__isnull=True).count()
messages.success(request,
_("Scans for this list have been scheduled. "+ \
"The total number of sites in the scanning queue "+ \
"is %i (including yours)." % num_scanning_sites))
else:
messages.warning(request,
_('All sites have been scanned recently. Please wait 30 minutes and try again.'))
return redirect(reverse('frontend:view_scan_list', args=(scan_list_id,)))
示例14: faq
# 需要導入模塊: from django import http [as 別名]
# 或者: from django.http import HttpRequest [as 別名]
def faq(request: HttpRequest):
num_scans = Site.objects.filter(scans__isnull=False).count()
num_scanning_sites = Scan.objects.filter(end__isnull=True).count()
# query = '''SELECT
# COUNT(jsonb_array_length("result"->'leaks'))
# FROM backend_scanresult
# WHERE backend_scanresult.scan_id IN (
# SELECT backend_site.last_scan_id
# FROM backend_site
# WHERE backend_site.last_scan_id IS NOT NULL)
# AND jsonb_array_length("result"->'leaks') > 0'''
#
# with connection.cursor() as cursor:
# cursor.execute(query)
# num_sites_failing_serverleak = cursor.fetchone()[0]
return render(request, 'frontend/faq.html', {
'num_scanning_sites': num_scanning_sites,
'num_scans': num_scans,
'num_sites': Site.objects.count(),
# 'num_sites_failing_serverleak': num_sites_failing_serverleak
})
示例15: test_get_ip_address_from_request
# 需要導入模塊: from django import http [as 別名]
# 或者: from django.http import HttpRequest [as 別名]
def test_get_ip_address_from_request(self):
""" get ip from request, make sure it is correct """
req = HttpRequest()
req.META["REMOTE_ADDR"] = "1.2.3.4"
ip = utils.get_ip_address_from_request(req)
self.assertEqual(ip, "1.2.3.4")
req = HttpRequest()
req.META["REMOTE_ADDR"] = "1.2.3.4 "
ip = utils.get_ip_address_from_request(req)
self.assertEqual(ip, "1.2.3.4")
req = HttpRequest()
req.META["REMOTE_ADDR"] = "192.168.100.34.y"
ip = utils.get_ip_address_from_request(req)
self.assertEqual(ip, "127.0.0.1")
req = HttpRequest()
req.META["REMOTE_ADDR"] = "cat"
ip = utils.get_ip_address_from_request(req)
self.assertEqual(ip, "127.0.0.1")
req = HttpRequest()
ip = utils.get_ip_address_from_request(req)
self.assertEqual(ip, "127.0.0.1")