Python django.http.request.HttpRequest() Examples

The following are 30 code examples of django.http.request.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.request , or try the search function .
Example #1
Source File: off_topic_channel_name.py    From site with MIT License 6 votes vote down vote up
def list(self, request: HttpRequest) -> Response:
        """
        DRF method for listing OffTopicChannelName entries.

        Called by the Django Rest Framework in response to the corresponding HTTP request.
        """
        if 'random_items' in request.query_params:
            param = request.query_params['random_items']
            try:
                random_count = int(param)
            except ValueError:
                raise ParseError(detail={'random_items': ["Must be a valid integer."]})

            if random_count <= 0:
                raise ParseError(detail={
                    'random_items': ["Must be a positive integer."]
                })

            queryset = self.get_queryset().order_by('?')[:random_count]
            serialized = self.serializer_class(queryset, many=True)
            return Response(serialized.data)

        queryset = self.get_queryset()
        serialized = self.serializer_class(queryset, many=True)
        return Response(serialized.data) 
Example #2
Source File: off_topic_channel_name.py    From site with MIT License 6 votes vote down vote up
def create(self, request: HttpRequest) -> Response:
        """
        DRF method for creating a new OffTopicChannelName.

        Called by the Django Rest Framework in response to the corresponding HTTP request.
        """
        if 'name' in request.query_params:
            create_data = {'name': request.query_params['name']}
            serializer = OffTopicChannelNameSerializer(data=create_data)
            serializer.is_valid(raise_exception=True)
            serializer.save()
            return Response(create_data, status=HTTP_201_CREATED)

        else:
            raise ParseError(detail={
                'name': ["This query parameter is required."]
            }) 
Example #3
Source File: node_action.py    From maas with GNU Affero General Public License v3.0 6 votes vote down vote up
def compile_node_actions(node, user, request=None, classes=ACTION_CLASSES):
    """Provide :class:`NodeAction` objects for given request.

    :param node: The :class:`Node` that the request pertains to.
    :param user: The :class:`User` making the request.
    :param request: The :class:`HttpRequest` being serviced.  It may be used
        to obtain information about the OAuth token being used.
    :return: An :class:`OrderedDict` mapping applicable actions' display names
        to corresponding :class:`NodeAction` instances.  The dict is ordered
        for consistent display.
    """
    actions = (action_class(node, user, request) for action_class in classes)
    return OrderedDict(
        (action.name, action)
        for action in actions
        if action.is_actionable() and action.is_permitted()
    ) 
Example #4
Source File: request.py    From esdc-ce with Apache License 2.0 6 votes vote down vote up
def get_dummy_request(dc, method=None, user=None, system_user=False):
    """
    Return dummy request object.
    """
    request = HttpRequest()
    request.csrf_processing_done = True
    request.dc = dc

    if method:
        request = set_request_method(request, method, copy_request=False)

    if system_user:
        from api.task.utils import get_system_task_user
        request.user = get_system_task_user()
    elif user:
        request.user = user

    return request 
Example #5
Source File: nomination.py    From site with MIT License 6 votes vote down vote up
def create(self, request: HttpRequest, *args, **kwargs) -> Response:
        """
        DRF method for creating a Nomination.

        Called by the Django Rest Framework in response to the corresponding HTTP request.
        """
        for field in request.data:
            if field in self.frozen_on_create:
                raise ValidationError({field: ['This field cannot be set at creation.']})

        user_id = request.data.get("user")
        if Nomination.objects.filter(active=True, user__id=user_id).exists():
            raise ValidationError({'active': ['There can only be one active nomination.']})

        serializer = self.get_serializer(
            data=ChainMap(
                request.data,
                {"active": True}
            )
        )
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) 
Example #6
Source File: middleware.py    From django-request-profiler with MIT License 6 votes vote down vote up
def process_view(
        self,
        request: HttpRequest,
        view_func: Callable,
        view_args: Any,
        view_kwargs: Any,
    ) -> None:
        """Add view_func to the profiler info."""
        # force the creation of a valid session by saving it.
        if (
            hasattr(request, "session")
            and request.session.session_key is None
            and settings.STORE_ANONYMOUS_SESSIONS is True
        ):
            request.session.save()

        if hasattr(view_func, "__name__"):
            request.profiler.view_func_name = view_func.__name__
        else:
            request.profiler.view_func_name = view_func.__class__.__name__ 
Example #7
Source File: tests.py    From django-admin-easy with MIT License 5 votes vote down vote up
def test_response_whitout_message(self):
        from django.contrib.messages.storage import default_storage

        request = HttpRequest()
        request.GET = QueryDict('test=asd')
        request.session = SessionStore('asd')
        request._messages = default_storage(request)

        response = easy.action_response(request)
        self.assertEqual(len(request._messages._queued_messages), 0)

        self.assertEqual(response.status_code, 302)
        self.assertEqual(response['Location'], './?test=asd') 
Example #8
Source File: pytest.py    From openwisp-controller with GNU General Public License v3.0 5 votes vote down vote up
def _force_login(self, user, backend=None):
        engine = importlib.import_module(settings.SESSION_ENGINE)
        request = HttpRequest()
        request.session = engine.SessionStore()
        login(request, user, backend)
        request.session.save()
        return request.session 
Example #9
Source File: utils.py    From cjworkbench with GNU Affero General Public License v3.0 5 votes vote down vote up
def log_user_event_from_request(
    request: HttpRequest, event: str, metadata: Optional[Dict[str, Any]] = None
) -> None:
    return _log_user_event(
        request.user, Headers.from_META(request.META), event, metadata
    ) 
Example #10
Source File: middleware.py    From django-request-token with MIT License 5 votes vote down vote up
def process_exception(
        self, request: HttpRequest, exception: Exception
    ) -> HttpResponse:
        """Handle all InvalidTokenErrors."""
        if isinstance(exception, InvalidTokenError):
            logger.exception("JWT request token error")
            response = _403(request, exception)
            if getattr(request, "token", None):
                request.token.log(request, response, error=exception)
            return response 
Example #11
Source File: middleware.py    From django-request-token with MIT License 5 votes vote down vote up
def _403(request: HttpRequest, exception: Exception) -> HttpResponseForbidden:
    """Render HttpResponseForbidden for exception."""
    if FOUR03_TEMPLATE:
        html = loader.render_to_string(
            template_name=FOUR03_TEMPLATE,
            context={"token_error": str(exception), "exception": exception},
            request=request,
        )
        return HttpResponseForbidden(html, reason=str(exception))
    return HttpResponseForbidden(reason=str(exception)) 
Example #12
Source File: tests.py    From django-admin-easy with MIT License 5 votes vote down vote up
def test_exist_view(self):
        request = HttpRequest()
        response1 = self.admin.easy_list_view(request, 'test')
        response2 = self.admin.easy_object_view(request, 1, 'test')

        self.assertEqual(response1.status_code, 200)
        self.assertEqual(response2.status_code, 200) 
Example #13
Source File: tests.py    From django-admin-easy with MIT License 5 votes vote down vote up
def test_not_exist_view(self):
        from django.contrib.messages.storage import default_storage

        request = HttpRequest()
        request.session = SessionStore('asd')
        request._messages = default_storage(request)

        response1 = self.admin.easy_list_view(request, 'not')
        response2 = self.admin.easy_object_view(request, 1, 'not')

        self.assertEqual(response1.status_code, 302)
        self.assertEqual(response2.status_code, 302)
        self.assertEqual(len(request._messages._queued_messages), 2) 
Example #14
Source File: tests.py    From django-admin-easy with MIT License 5 votes vote down vote up
def test_response_normal(self):
        from django.contrib.messages.storage import default_storage

        request = HttpRequest()
        request.GET = QueryDict('test=asd')
        request.session = SessionStore('asd')
        request._messages = default_storage(request)

        response = easy.action_response(request, 'Some message')

        self.assertEqual(len(request._messages._queued_messages), 1)
        self.assertEqual(response.status_code, 302)
        self.assertEqual(response['Location'], './?test=asd') 
Example #15
Source File: tests.py    From django-admin-easy with MIT License 5 votes vote down vote up
def test_response_without_querystring(self):
        from django.contrib.messages.storage import default_storage

        request = HttpRequest()
        request.GET = QueryDict('test=asd')
        request.session = SessionStore('asd')
        request._messages = default_storage(request)

        response = easy.action_response(request, 'Some message', keep_querystring=False)

        self.assertEqual(len(request._messages._queued_messages), 1)
        self.assertEqual(response.status_code, 302)
        self.assertEqual(response['Location'], '.') 
Example #16
Source File: bokeh_handler.py    From tethys with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def with_request(handler):
    @wraps(handler)
    def wrapper(doc: Document):
        bokeh_request = doc.session_context.request
        bokeh_request.pop('scheme')
        django_request = HttpRequest()
        for k, v in bokeh_request.items():
            setattr(django_request, k, v)
        doc.request = django_request
        return handler(doc)
    return wrapper 
Example #17
Source File: tests.py    From django-admin-easy with MIT License 5 votes vote down vote up
def test_response_whitout_GET(self):
        from django.contrib.messages.storage import default_storage

        request = HttpRequest()
        request.session = SessionStore('asd')
        request._messages = default_storage(request)

        response = easy.action_response(request)

        self.assertEqual(len(request._messages._queued_messages), 0)
        self.assertEqual(response.status_code, 302)
        self.assertEqual(response['Location'], '.') 
Example #18
Source File: test_auth_helpers.py    From django-modern-rpc with MIT License 5 votes vote down vote up
def test_http_basic_get_user():

    # Basic django request, without authentication info
    request = HttpRequest()

    # Standard middlewares were not applied on this request
    user = http_basic_auth_get_user(request)

    assert user is not None
    assert user_is_anonymous(user) 
Example #19
Source File: middleware.py    From polemarch with GNU Affero General Public License v3.0 5 votes vote down vote up
def handler(self, request: HttpRequest, response: HttpResponse) -> HttpResponse:
        # pylint: disable=unused-argument
        response['Polemarch-Version'] = self.get_setting('POLEMARCH_VERSION')
        response['Polemarch-Timezone'] = self.get_setting('TIME_ZONE')
        return response 
Example #20
Source File: test_ajax.py    From Kiwi with GNU General Public License v2.0 5 votes vote down vote up
def setUpTestData(cls):
        cls.request = HttpRequest()

        cls.test_plan = TestPlanFactory()
        cls.test_case = TestCaseFactory() 
Example #21
Source File: util_test.py    From micromasters with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def setUp(self):
        super().setUp()
        self.request = HttpRequest() 
Example #22
Source File: http.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def make_HttpRequest(server_name=None, server_port=None, http_host=None):
    if server_name is None:
        server_name = "testserver"
    if server_port is None:
        server_port = 80
    request = HttpRequest()
    request.META["SERVER_NAME"] = server_name
    request.META["SERVER_PORT"] = server_port
    if http_host is not None:
        request.META["HTTP_HOST"] = http_host
    return request 
Example #23
Source File: tasks.py    From django-is-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_rest_request(user, rest_context):
    request = HttpRequest()
    request._rest_context = rest_context
    request.user = user
    request.kwargs = {}
    return request 
Example #24
Source File: test_channels.py    From django-loci with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _force_login(self, user, backend=None):
        engine = importlib.import_module(settings.SESSION_ENGINE)
        request = HttpRequest()
        request.session = engine.SessionStore()
        login(request, user, backend)
        request.session.save
        return request.session 
Example #25
Source File: tests.py    From nplusone with MIT License 5 votes vote down vote up
def test_middleware_no_process_request():
    middleware = NPlusOneMiddleware()
    req, resp = HttpRequest(), HttpResponse()
    processed = middleware.process_response(req, resp)
    assert processed is resp 
Example #26
Source File: test_sites.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_with_server_name(self):
        request = HttpRequest()
        request.META = {
            'SERVER_NAME': 'example.com',
            'SERVER_PORT': 80
        }
        self.assertEqual(Site.find_for_request(request), self.site) 
Example #27
Source File: responses.py    From django-telegram-bot with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def render(self):
        if not self.template_name:
            return None
        try:
            logger.debug("Template name: %s" % self.template_name)
            template = get_template(self.template_name)      
        except TemplateDoesNotExist:
            logger.debug("Template not found: %s" % self.template_name)
            return None
        # TODO: Avoid using a null HttRequest to context processors
        ctx = RequestContext(HttpRequest(), self.ctx)
        return template.render(ctx) 
Example #28
Source File: base.py    From Wagtail-Pipit with MIT License 5 votes vote down vote up
def get_context(self, request: HttpRequest, *args, **kwargs) -> Dict[str, Any]:
        context = super().get_context(request, *args, **kwargs)

        return {**context, "props": self.get_component_data({"request": request})} 
Example #29
Source File: base.py    From Wagtail-Pipit with MIT License 5 votes vote down vote up
def serve(self, request: HttpRequest, *args, **kwargs) -> HttpResponse:
        if self.should_serve_json(request):
            json = self.get_component_data({"request": request})
            return JsonResponse(json)

        return super().serve(request, *args, **kwargs) 
Example #30
Source File: base.py    From Wagtail-Pipit with MIT License 5 votes vote down vote up
def should_serve_json(request: HttpRequest) -> bool:
        return (
            request.GET.get("format", None) == "json"
            or request.content_type == "application/json"
        )