Python django.http.HttpRequest() Examples

The following are 30 code examples of django.http.HttpRequest(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.http , or try the search function .
Example #1
Source File: views.py    From coursys with GNU General Public License v3.0 6 votes vote down vote up
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) 
Example #2
Source File: views.py    From coursys with GNU General Public License v3.0 6 votes vote down vote up
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() 
Example #3
Source File: test_serializer_introspector.py    From py2swagger with MIT License 6 votes vote down vote up
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') 
Example #4
Source File: views.py    From coursys with GNU General Public License v3.0 6 votes vote down vote up
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) 
Example #5
Source File: views.py    From coursys with GNU General Public License v3.0 6 votes vote down vote up
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) 
Example #6
Source File: method.py    From py2swagger with MIT License 6 votes vote down vote up
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 
Example #7
Source File: views.py    From coursys with GNU General Public License v3.0 6 votes vote down vote up
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.') 
Example #8
Source File: views.py    From coursys with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #9
Source File: client.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def logout(self):
        """
        Removes the authenticated user's cookies and session object.

        Causes the authenticated user to be logged out.
        """
        from django.contrib.auth import get_user, logout

        request = HttpRequest()
        engine = import_module(settings.SESSION_ENGINE)
        if self.session:
            request.session = self.session
            request.user = get_user(request)
        else:
            request.session = engine.SessionStore()
        logout(request)
        self.cookies = SimpleCookie() 
Example #10
Source File: views.py    From coursys with GNU General Public License v3.0 6 votes vote down vote up
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() 
Example #11
Source File: tests.py    From django-defender with Apache License 2.0 6 votes vote down vote up
def test_get_user_attempts(self):
        """ Get the user attempts make sure they are correct """
        ip_attempts = random.randint(3, 12)
        username_attempts = random.randint(3, 12)
        for i in range(0, ip_attempts):
            utils.increment_key(utils.get_ip_attempt_cache_key("1.2.3.4"))
        for i in range(0, username_attempts):
            utils.increment_key(utils.get_username_attempt_cache_key("foobar"))
        req = HttpRequest()
        req.POST["username"] = "foobar"
        req.META["HTTP_X_REAL_IP"] = "1.2.3.4"
        self.assertEqual(
            utils.get_user_attempts(req), max(ip_attempts, username_attempts)
        )

        req = HttpRequest()
        req.POST["username"] = "foobar"
        req.META["HTTP_X_REAL_IP"] = "5.6.7.8"
        self.assertEqual(utils.get_user_attempts(req), username_attempts)

        req = HttpRequest()
        req.POST["username"] = "barfoo"
        req.META["HTTP_X_REAL_IP"] = "1.2.3.4"
        self.assertEqual(utils.get_user_attempts(req), ip_attempts) 
Example #12
Source File: views.py    From coursys with GNU General Public License v3.0 6 votes vote down vote up
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) 
Example #13
Source File: tests.py    From django-defender with Apache License 2.0 6 votes vote down vote up
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") 
Example #14
Source File: views.py    From PrivacyScore with GNU General Public License v3.0 6 votes vote down vote up
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
    }) 
Example #15
Source File: tests.py    From trove-dashboard with Apache License 2.0 6 votes vote down vote up
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) 
Example #16
Source File: tile_model_tests.py    From arches with GNU Affero General Public License v3.0 6 votes vote down vote up
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) 
Example #17
Source File: views.py    From PrivacyScore with GNU General Public License v3.0 6 votes vote down vote up
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,))) 
Example #18
Source File: views.py    From PrivacyScore with GNU General Public License v3.0 5 votes vote down vote up
def lookup(request: HttpRequest) -> HttpResponse:
    return render(request, 'frontend/lookup.html') 
Example #19
Source File: views.py    From PrivacyScore with GNU General Public License v3.0 5 votes vote down vote up
def team(request: HttpRequest):
    return render(request, 'frontend/team.html') 
Example #20
Source File: tests_query_params.py    From koku with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_constructor_invalid_uri(self):
        """Test that ValidationError is raised with an invalid uri."""
        fake_request = Mock(spec=HttpRequest, GET=Mock(urlencode=Mock(return_value=self.FAKE.paragraph())))
        fake_view = Mock(
            spec=ReportView,
            provider=self.FAKE.word(),
            query_handler=Mock(provider=self.FAKE.word()),
            report="tags",
            serializer=Mock,
            tag_handler=[],
        )
        with self.assertRaises(ValidationError):
            QueryParameters(fake_request, fake_view) 
Example #21
Source File: views.py    From PrivacyScore with GNU General Public License v3.0 5 votes vote down vote up
def scan_site_created(request: HttpRequest, site_id: int) -> HttpResponse:
    site = get_object_or_404(Site, pk=site_id)
    num_scanning_sites = Scan.objects.filter(end__isnull=True).count()
    return render(request, 'frontend/scan_site_created.html', {
        'site': site,
        'num_scanning_sites': num_scanning_sites
    }) 
Example #22
Source File: views.py    From PrivacyScore with GNU General Public License v3.0 5 votes vote down vote up
def legal(request: HttpRequest) -> HttpResponse:
    return render(request, 'frontend/legal.html')


# TODO: Rename function (i.e. create_scan_list) 
Example #23
Source File: views.py    From PrivacyScore with GNU General Public License v3.0 5 votes vote down vote up
def login(request: HttpRequest) -> HttpResponse:
    return render(request, 'frontend/login.html') 
Example #24
Source File: views.py    From PrivacyScore with GNU General Public License v3.0 5 votes vote down vote up
def scan_site(request: HttpRequest, site_id: Union[int, None] = None) -> HttpResponse:
    """Schedule the scan of a site."""
    if site_id:
        site = get_object_or_404(
            Site.objects.annotate_most_recent_scan_start() \
            .annotate_most_recent_scan_end_or_null(),
            pk=site_id)
    else:
        # no site_id supplied
        form = SingleSiteForm(request.POST)
        if form.is_valid():
            site, created = Site.objects.annotate_most_recent_scan_start() \
            .annotate_most_recent_scan_end_or_null().get_or_create(
                url=form.cleaned_data.get('url'))
            if created:
                site.last_scan__end_or_null = None
                site.last_scan__start = None
        else:
            return render(request, 'frontend/create_site.html', {
                'form': form,
            })
    status_code = site.scan()
    if status_code == Site.SCAN_OK:
        if not site_id: # if the site is new we want to show the dog
            return redirect(reverse('frontend:scan_site_created', args=(site.pk,)))
        else:
            num_scanning_sites = Scan.objects.filter(end__isnull=True).count()
            messages.success(request,
                _("A scan of the site has been scheduled. "+ \
                  "The total number of sites in the scanning queue "+ \
                  "is %i (including yours)." % num_scanning_sites))
            return redirect(reverse('frontend:view_site', args=(site.pk,)))
    elif status_code == Site.SCAN_COOLDOWN:
        messages.warning(request,
            _('The site is already scheduled for scanning or it has been scanned recently. No scan was scheduled.'))
    elif status_code == Site.SCAN_BLACKLISTED:
        messages.warning(request,
            _('The operator of this website requested to be blacklisted, scanning this website is not possible, sorry.'))
    return redirect(reverse('frontend:view_site', args=(site.pk,))) 
Example #25
Source File: views.py    From PrivacyScore with GNU General Public License v3.0 5 votes vote down vote up
def scan_list_csv(request: HttpRequest, scan_list_id: int) -> HttpResponse:
    scan_list = get_object_or_404(ScanList.objects.prefetch_columns(), pk=scan_list_id)
    resp = HttpResponse(content_type='text/csv')
    writer = csv.writer(resp, dialect='excel', delimiter=';')
    writer.writerow(['URL'] + [col.name for col in scan_list.ordered_columns])
    for site in scan_list.sites.prefetch_column_values(scan_list):
        writer.writerow([site.url] + [col.value for col in site.ordered_column_values])
    return resp 
Example #26
Source File: views.py    From PrivacyScore with GNU General Public License v3.0 5 votes vote down vote up
def site_result_json(request: HttpRequest, site_id: int) -> HttpResponse:
    if 'at' in request.GET:
        # Check that the site even exists
        site = get_object_or_404(Site, pk=site_id)

        # TODO sanity check timestamp
        try:
            timestamp = datetime.strptime(request.GET['at'], "%Y-%m-%d")
        except:
            return render(request, 'frontend/site_result_json.html', {'site': site, 'highlighted_code': 'Incorrect timestamp format'})
        try:
            scan = Scan.objects.filter(site=site).filter(end__lte=timestamp).order_by('-end').first()
            scan_result = ScanResult.objects.get(scan=scan).result
        except Exception as e:
            scan_result = None
    else:
        site = get_object_or_404(Site.objects.annotate_most_recent_scan_result(), pk=site_id)
        scan_result = site.last_scan__result if site.last_scan__result else {}
    if 'raw' in request.GET:
        return JsonResponse(scan_result)
    code = json.dumps(scan_result, indent=2)
    if scan_result is not None:
        highlighted_code = mark_safe(highlight(code, JsonLexer(), HtmlFormatter()))
    else:
        highlighted_code = 'No scan data found for these parameters'
    return render(request, 'frontend/site_result_json.html', {
        'site': site,
        'highlighted_code': highlighted_code
    }) 
Example #27
Source File: views.py    From PrivacyScore with GNU General Public License v3.0 5 votes vote down vote up
def user(request: HttpRequest) -> HttpResponse:
    return render(request, 'frontend/user.html') 
Example #28
Source File: test_unit.py    From Servo with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_homepage_error_without_cookies(self):
        request = HttpRequest()
        response = checkin.home(request)
        self.assertTrue(response.content.startswith("<!DOCTYPE html>"), response.content)
        self.assertIn('<title>An error occurred', response.content)
        self.assertTrue(response.content.endswith('</html>')) 
Example #29
Source File: views.py    From PrivacyScore with GNU General Public License v3.0 5 votes vote down vote up
def checks(request: HttpRequest):
    return render(request, 'frontend/checks.html') 
Example #30
Source File: views.py    From PrivacyScore with GNU General Public License v3.0 5 votes vote down vote up
def site_screenshot(request: HttpRequest, site_id: int) -> HttpResponse:
    """View a site and its most recent scan result (if any)."""
    site = get_object_or_404(Site, pk=site_id)

    screenshot = site.get_screenshot()
    if not screenshot:
        return HttpResponseNotFound(_('screenshot does not exist'))
    return HttpResponse(screenshot, content_type='image/png')