當前位置: 首頁>>代碼示例>>Python>>正文


Python request.Request方法代碼示例

本文整理匯總了Python中rest_framework.request.Request方法的典型用法代碼示例。如果您正苦於以下問題:Python request.Request方法的具體用法?Python request.Request怎麽用?Python request.Request使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在rest_framework.request的用法示例。


在下文中一共展示了request.Request方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: test_browsable_renderer_put_render

# 需要導入模塊: from rest_framework import request [as 別名]
# 或者: from rest_framework.request import Request [as 別名]
def test_browsable_renderer_put_render(input_put_view, decorator):
    """
    Test, that PUT method works with BrowsableAPIRenderer
    This was not working in the past, because of `_get_serializer`
    didn't allow `instance parameter.
    """
    data = {'blah': 'blah'}
    method = 'PUT'
    request = rest_request.Request(APIRequestFactory().get('blah'))
    output_view = decorator(input_put_view)
    wrapper_cls = _get_view_class(output_view)
    test_view_instance = wrapper_cls()

    renderer = renderers.BrowsableAPIRenderer()
    renderer.accepted_media_type = None
    renderer.renderer_context = {}
    response = renderer.get_raw_data_form(
        data, test_view_instance, method, request,
    )
    assert response.data == {} 
開發者ID:apragacz,項目名稱:django-rest-registration,代碼行數:22,代碼來源:test_api_view_serializer_class_getter.py

示例2: save_scan_list

# 需要導入模塊: from rest_framework import request [as 別名]
# 或者: from rest_framework.request import Request [as 別名]
def save_scan_list(request: Request) -> Response:
    """Save a new list."""
    try:
        with transaction.atomic():
            scan_list = ScanList.objects.create(
                name=request.data['listname'],
                description=request.data['description'],
                private=bool(request.data['isprivate']),
                user=request.user if request.user.is_authenticated else None)

            scan_list.save_tags(request.data['tags'])

            # save columns
            scan_list.save_columns(request.data['columns'])

            return Response({
                'list_id': scan_list.pk,
                'token': scan_list.token
            }, status=201)
    except KeyError:
        raise ParseError 
開發者ID:PrivacyScore,項目名稱:PrivacyScore,代碼行數:23,代碼來源:views.py

示例3: delete_scan_list

# 需要導入模塊: from rest_framework import request [as 別名]
# 或者: from rest_framework.request import Request [as 別名]
def delete_scan_list(request: Request, token: str) -> Response:
    """Update an existing list."""
    # TODO: Access control (Or is token sufficient)?
    try:
        scan_list = ScanList.objects.get(token=token)

        # all related objects CASCADE automatically.
        scan_list.delete()

        return Response({
            'type': 'success',
            'message': 'ok',
        })
    except KeyError as e:
        raise ParseError
    except ScanList.DoesNotExist:
        raise NotFound


# TODO: Why POST?
# TODO: Add a filter option to get_lists and get rid of this search method 
開發者ID:PrivacyScore,項目名稱:PrivacyScore,代碼行數:23,代碼來源:views.py

示例4: process_response

# 需要導入模塊: from rest_framework import request [as 別名]
# 或者: from rest_framework.request import Request [as 別名]
def process_response(cls, request, response):
        if request.META.get('HTTP_ORIGIN'):
            response['Access-Control-Allow-Origin'] = request.META['HTTP_ORIGIN']
            response['Access-Control-Allow-Credentials'] = 'true'
        # setattr(response, 'Access-Control-Allow-Origin', "*")
        response['X-Frame-Options'] = 'ALLOW-FROM *.007.pub'

        from rest_framework.request import Request

        try:
            if isinstance(request, Request):
                request = request._request
            end = time.time()
            exectime = end - request.start

            logger.info("stat exectime: time: %fs  path:%s  querystring:%s" % (
                         exectime, request.path, request.META['QUERY_STRING']))

        except Exception as e:
            logging.error(e)

        return response 
開發者ID:007gzs,項目名稱:dingtalk-django-example,代碼行數:24,代碼來源:middlewares.py

示例5: test_ocpcpuview_success

# 需要導入模塊: from rest_framework import request [as 別名]
# 或者: from rest_framework.request import Request [as 別名]
def test_ocpcpuview_success(self, mock_handler):
        """Test OCP cpu view report."""
        mock_handler.return_value.execute_query.return_value = self.report_ocp_cpu
        params = {
            "group_by[node]": "*",
            "filter[resolution]": "monthly",
            "filter[time_scope_value]": "-1",
            "filter[time_scope_units]": "month",
        }
        user = User.objects.get(username=self.user_data["username"])

        django_request = HttpRequest()
        if not django_request.META.get("HTTP_HOST"):
            django_request.META["HTTP_HOST"] = "testhost"

        qd = QueryDict(mutable=True)
        qd.update(params)
        django_request.GET = qd
        request = Request(django_request)
        request.user = user

        response = OCPCpuView().get(request)
        self.assertIsInstance(response, Response)
        self.assertEqual(response.status_code, status.HTTP_200_OK) 
開發者ID:project-koku,項目名稱:koku,代碼行數:26,代碼來源:tests_views.py

示例6: test_ocpmemview_success

# 需要導入模塊: from rest_framework import request [as 別名]
# 或者: from rest_framework.request import Request [as 別名]
def test_ocpmemview_success(self, mock_handler):
        """Test OCP memory view report."""
        mock_handler.return_value.execute_query.return_value = self.report_ocp_mem
        params = {
            "group_by[node]": "*",
            "filter[resolution]": "monthly",
            "filter[time_scope_value]": "-1",
            "filter[time_scope_units]": "month",
        }
        user = User.objects.get(username=self.user_data["username"])

        django_request = HttpRequest()
        if not django_request.META.get("HTTP_HOST"):
            django_request.META["HTTP_HOST"] = "testhost"

        qd = QueryDict(mutable=True)
        qd.update(params)
        django_request.GET = qd
        request = Request(django_request)
        request.user = user

        response = OCPMemoryView().get(request)
        self.assertIsInstance(response, Response)
        self.assertEqual(response.status_code, status.HTTP_200_OK) 
開發者ID:project-koku,項目名稱:koku,代碼行數:26,代碼來源:tests_views.py

示例7: test_costview_with_units_success

# 需要導入模塊: from rest_framework import request [as 別名]
# 或者: from rest_framework.request import Request [as 別名]
def test_costview_with_units_success(self, mock_handler):
        """Test unit conversion succeeds in AzureCostView."""
        mock_handler.return_value.execute_query.return_value = self.report
        params = {
            "group_by[subscription_guid]": "*",
            "filter[resolution]": "monthly",
            "filter[time_scope_value]": "-1",
            "filter[time_scope_units]": "month",
            "units": "byte",
            "SERVER_NAME": "",
        }
        user = User.objects.get(username=self.user_data["username"])

        django_request = HttpRequest()
        qd = QueryDict(mutable=True)
        qd.update(params)
        django_request.GET = qd
        request = Request(django_request)
        request.user = user

        response = AzureCostView().get(request)
        self.assertIsInstance(response, Response) 
開發者ID:project-koku,項目名稱:koku,代碼行數:24,代碼來源:tests_views.py

示例8: confirm_email

# 需要導入模塊: from rest_framework import request [as 別名]
# 或者: from rest_framework.request import Request [as 別名]
def confirm_email(request: Request) -> Response:
    if not (request.GET.get("token") and request.GET.get("email")):
        return render_error_response(
            "email and token arguments required.", content_type="text/html"
        )

    try:
        account = PolarisStellarAccount.objects.get(
            user__email=request.GET.get("email"),
            confirmation_token=request.GET.get("token"),
        )
    except PolarisStellarAccount.DoesNotExist:
        return render_error_response(
            "User with email and token does not exist", content_type="text/html"
        )

    account.confirmed = True
    account.save()

    return Response(template_name="email_confirmed.html") 
開發者ID:stellar,項目名稱:django-polaris,代碼行數:22,代碼來源:views.py

示例9: _generate_jwt

# 需要導入模塊: from rest_framework import request [as 別名]
# 或者: from rest_framework.request import Request [as 別名]
def _generate_jwt(request: Request, envelope_xdr: str) -> str:
        """
        Generates the JSON web token from the challenge transaction XDR.

        See: https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0010.md#token
        """
        issued_at = time.time()
        transaction_envelope, source_account = read_challenge_transaction(
            envelope_xdr, settings.SIGNING_KEY, settings.STELLAR_NETWORK_PASSPHRASE
        )
        logger.info(
            f"Challenge verified, generating SEP-10 token for account {source_account}"
        )
        hash_hex = binascii.hexlify(transaction_envelope.hash()).decode()
        jwt_dict = {
            "iss": os.path.join(settings.HOST_URL, "auth"),
            "sub": source_account,
            "iat": issued_at,
            "exp": issued_at + 24 * 60 * 60,
            "jti": hash_hex,
        }
        encoded_jwt = jwt.encode(jwt_dict, settings.SERVER_JWT_KEY, algorithm="HS256")
        return encoded_jwt.decode("ascii") 
開發者ID:stellar,項目名稱:django-polaris,代碼行數:25,代碼來源:views.py

示例10: interactive_url

# 需要導入模塊: from rest_framework import request [as 別名]
# 或者: from rest_framework.request import Request [as 別名]
def interactive_url(
        self,
        request: Request,
        transaction: Transaction,
        asset: Asset,
        amount: Optional[Decimal],
        callback: Optional[str],
    ) -> Optional[str]:
        """
        Override this function to provide the wallet a non-Polaris endpoint
        to begin the interactive flow. If the `amount` or `callback` arguments
        are not ``None``, make sure you include them in the URL returned.

        :return: a URL to be used as the entry point for the interactive
            deposit flow
        """
        pass 
開發者ID:stellar,項目名稱:django-polaris,代碼行數:19,代碼來源:transactions.py

示例11: complete_interactive_deposit

# 需要導入模塊: from rest_framework import request [as 別名]
# 或者: from rest_framework.request import Request [as 別名]
def complete_interactive_deposit(request: Request) -> Response:
    """
    GET /transactions/deposit/interactive/complete

    Updates the transaction status to pending_user_transfer_start and
    redirects to GET /more_info. A `callback` can be passed in the URL
    to be used by the more_info template javascript.
    """
    transaction_id = request.GET.get("transaction_id")
    callback = request.GET.get("callback")
    if not transaction_id:
        return render_error_response(
            _("Missing id parameter in URL"), content_type="text/html"
        )
    Transaction.objects.filter(id=transaction_id).update(
        status=Transaction.STATUS.pending_user_transfer_start
    )
    logger.info(f"Hands-off interactive flow complete for transaction {transaction_id}")
    url, args = (
        reverse("more_info"),
        urlencode({"id": transaction_id, "callback": callback}),
    )
    return redirect(f"{url}?{args}") 
開發者ID:stellar,項目名稱:django-polaris,代碼行數:25,代碼來源:deposit.py

示例12: check_authentication

# 需要導入模塊: from rest_framework import request [as 別名]
# 或者: from rest_framework.request import Request [as 別名]
def check_authentication(content_type: str = "text/html") -> Callable:
    """
    Authentication decorator for POST /interactive endoints
    """

    def decorator(view) -> Callable:
        def wrapper(request: Request, *args, **kwargs) -> Response:
            try:
                check_authentication_helper(request)
            except ValueError as e:
                return render_error_response(
                    str(e), content_type=content_type, status_code=403
                )
            else:
                return view(request)

        return wrapper

    return decorator 
開發者ID:stellar,項目名稱:django-polaris,代碼行數:21,代碼來源:utils.py

示例13: authenticate_session

# 需要導入模塊: from rest_framework import request [as 別名]
# 或者: from rest_framework.request import Request [as 別名]
def authenticate_session(content_type: str = "text/html") -> Callable:
    """
    Authentication decorator for GET /interactive endpoints
    """

    def decorator(view) -> Callable:
        def wrapper(request: Request, *args, **kwargs) -> Response:
            try:
                authenticate_session_helper(request)
            except ValueError as e:
                return render_error_response(
                    str(e), content_type=content_type, status_code=403
                )
            else:
                return view(request)

        return wrapper

    return decorator 
開發者ID:stellar,項目名稱:django-polaris,代碼行數:21,代碼來源:utils.py

示例14: check_authentication_helper

# 需要導入模塊: from rest_framework import request [as 別名]
# 或者: from rest_framework.request import Request [as 別名]
def check_authentication_helper(r: Request):
    """
    Checks that the session associated with the request is authenticated
    """
    # Don't authenticate in local mode, since session cookies will not be
    # included in request/response headers without HTTPS
    if settings.LOCAL_MODE:
        return

    if not r.session.get("authenticated"):
        raise ValueError(_("Session is not authenticated"))

    transaction_qs = Transaction.objects.filter(
        id=r.GET.get("transaction_id"), stellar_account=r.session.get("account")
    )
    if not transaction_qs.exists():
        raise ValueError(_("Transaction for account not found")) 
開發者ID:stellar,項目名稱:django-polaris,代碼行數:19,代碼來源:utils.py

示例15: generate_interactive_jwt

# 需要導入模塊: from rest_framework import request [as 別名]
# 或者: from rest_framework.request import Request [as 別名]
def generate_interactive_jwt(
    request: Request, transaction_id: str, account: str
) -> str:
    """
    Generates a 30-second JWT for the client to use in the GET URL for
    the interactive flow.
    """
    issued_at = time.time()
    payload = {
        "iss": request.build_absolute_uri(request.path),
        "iat": issued_at,
        "exp": issued_at + 30,
        "sub": account,
        "jti": transaction_id,
    }
    encoded_jwt = jwt.encode(payload, settings.SERVER_JWT_KEY, algorithm="HS256")
    return encoded_jwt.decode("ascii") 
開發者ID:stellar,項目名稱:django-polaris,代碼行數:19,代碼來源:utils.py


注:本文中的rest_framework.request.Request方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。