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


Python request.Request方法代碼示例

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


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

示例1: openapi_validation_error

# 需要導入模塊: from pyramid import request [as 別名]
# 或者: from pyramid.request import Request [as 別名]
def openapi_validation_error(
    context: t.Union[RequestValidationError, ResponseValidationError], request: Request
) -> Response:
    """Render any validation errors as JSON."""
    if isinstance(context, RequestValidationError):
        logger.warning(context)
    if isinstance(context, ResponseValidationError):
        logger.error(context)

    extract_errors = request.registry.settings["pyramid_openapi3_extract_errors"]
    errors = list(extract_errors(request, context.errors))

    # If validation failed for request, it is user's fault (-> 400), but if
    # validation failed for response, it is our fault (-> 500)
    if isinstance(context, RequestValidationError):
        status_code = 400
        for error in context.errors:
            if isinstance(error, InvalidSecurity):
                status_code = 401

    if isinstance(context, ResponseValidationError):
        status_code = 500

    return exception_response(status_code, json_body=errors) 
開發者ID:Pylons,項目名稱:pyramid_openapi3,代碼行數:26,代碼來源:__init__.py

示例2: get_user_id_via_auth_cookie

# 需要導入模塊: from pyramid import request [as 別名]
# 或者: from pyramid.request import Request [as 別名]
def get_user_id_via_auth_cookie(request: Request) -> Optional[int]:
    if auth_cookie_name not in request.cookies:
        return None

    val = request.cookies[auth_cookie_name]
    parts = val.split(':')
    if len(parts) != 2:
        return None

    user_id = parts[0]
    hash_val = parts[1]
    hash_val_check = __hash_text(user_id)
    if hash_val != hash_val_check:
        print("Warning: Hash mismatch, invalid cookie value")
        return None

    return try_int(user_id) 
開發者ID:talkpython,項目名稱:data-driven-web-apps-with-pyramid-and-sqlalchemy,代碼行數:19,代碼來源:cookie_auth.py

示例3: __init__

# 需要導入模塊: from pyramid import request [as 別名]
# 或者: from pyramid.request import Request [as 別名]
def __init__(self, request: Request):
        super().__init__(request)

        self.package_name = request.matchdict.get('package_name')
        self.package = package_service.find_package_by_name(self.package_name)

        self.latest_version = '0.0.0'
        self.latest_release = None

        if self.package.releases:
            self.latest_release = self.package.releases[0]
            self.latest_version = '{}.{}.{}'.format(
                self.latest_release.major_ver,
                self.latest_release.minor_ver,
                self.latest_release.build_ver
            )

        self.release_version = self.latest_version
        self.maintainers = []
        self.is_latest = True 
開發者ID:talkpython,項目名稱:data-driven-web-apps-with-pyramid-and-sqlalchemy,代碼行數:22,代碼來源:package_details_viewmodel.py

示例4: __init__

# 需要導入模塊: from pyramid import request [as 別名]
# 或者: from pyramid.request import Request [as 別名]
def __init__(self, request: Request):
        super().__init__(request)

        self.package_name = request.matchdict.get('package_name')
        self.package = package_service.find_package_by_name(self.package_name)

        self.latest_version = '0.0.0'
        self.latest_release = None

        if self.package and self.package.releases:
            self.latest_release = self.package.releases[0]
            self.latest_version = '{}.{}.{}'.format(
                self.latest_release.major_ver,
                self.latest_release.minor_ver,
                self.latest_release.build_ver
            )

        self.release_version = self.latest_version
        self.maintainers = []
        self.is_latest = True 
開發者ID:talkpython,項目名稱:data-driven-web-apps-with-pyramid-and-sqlalchemy,代碼行數:22,代碼來源:package_details_viewmodel.py

示例5: register_post

# 需要導入模塊: from pyramid import request [as 別名]
# 或者: from pyramid.request import Request [as 別名]
def register_post(request: Request):
    email = request.POST.get('email')
    name = request.POST.get('name')
    password = request.POST.get('password')

    if not email or not name or not password:
        return {
            'email': email,
            'name': name,
            'password': password,
            'error': 'Some required fields are missing.',
            'user_id': cookie_auth.get_user_id_via_auth_cookie(request)
        }

    # create user
    user = user_service.create_user(email, name, password)
    cookie_auth.set_auth(request, user.id)

    return x.HTTPFound('/account')


# ################### LOGIN ################################# 
開發者ID:talkpython,項目名稱:data-driven-web-apps-with-pyramid-and-sqlalchemy,代碼行數:24,代碼來源:account_controller.py

示例6: login_post

# 需要導入模塊: from pyramid import request [as 別名]
# 或者: from pyramid.request import Request [as 別名]
def login_post(request: Request):
    data = request_dict.create(request)
    email = data.email
    password = data.password

    user = user_service.login_user(email, password)

    if not user:
        return {
            'email': email,
            'password': password,
            'error': 'The user could not found or the password is incorrect.',
            'user_id': cookie_auth.get_user_id_via_auth_cookie(request)
        }

    cookie_auth.set_auth(request, user.id)
    return x.HTTPFound('/account')


# ################### LOGOUT ################################# 
開發者ID:talkpython,項目名稱:data-driven-web-apps-with-pyramid-and-sqlalchemy,代碼行數:22,代碼來源:account_controller.py

示例7: __json__

# 需要導入模塊: from pyramid import request [as 別名]
# 或者: from pyramid.request import Request [as 別名]
def __json__(self, request: Request) -> t.Dict[str, str]:
        """JSON-renderer for this object."""
        return {"title": self.title}


# fmt: off
# Poor-man's in-memory database. Pre-populated with three TODO items. 
開發者ID:Pylons,項目名稱:pyramid_openapi3,代碼行數:9,代碼來源:app.py

示例8: get

# 需要導入模塊: from pyramid import request [as 別名]
# 或者: from pyramid.request import Request [as 別名]
def get(request: Request) -> t.List[Item]:
    """Serve the list of TODO items for GET requests."""
    return ITEMS 
開發者ID:Pylons,項目名稱:pyramid_openapi3,代碼行數:5,代碼來源:app.py

示例9: post

# 需要導入模塊: from pyramid import request [as 別名]
# 或者: from pyramid.request import Request [as 別名]
def post(request: Request) -> str:
    """Handle POST requests and create TODO items."""
    item = Item(title=request.openapi_validated.body["title"])
    ITEMS.append(item)
    return "Item added." 
開發者ID:Pylons,項目名稱:pyramid_openapi3,代碼行數:7,代碼來源:app.py

示例10: create

# 需要導入模塊: from pyramid import request [as 別名]
# 或者: from pyramid.request import Request [as 別名]
def create(
        cls: t.Type["PyramidOpenAPIRequestFactory"], request: Request
    ) -> "OpenAPIRequest":
        """Create OpenAPIRequest from Pyramid Request."""
        method = request.method.lower()
        path_pattern = (
            request.matched_route.pattern
            if request.matched_route
            else request.path_info
        )
        # a path pattern is not normalized in pyramid so it may or may not
        # start with a leading /, so normalize it here
        path_pattern = path_pattern.lstrip("/")
        full_url_pattern = request.application_url + "/" + path_pattern

        parameters = RequestParameters(
            path=request.matchdict,
            query=request.GET,
            header=request.headers,
            cookie=request.cookies,
        )

        return OpenAPIRequest(
            full_url_pattern=full_url_pattern,
            method=method,
            parameters=parameters,
            body=request.body,
            mimetype=request.content_type,
        ) 
開發者ID:Pylons,項目名稱:pyramid_openapi3,代碼行數:31,代碼來源:wrappers.py

示例11: openapi_view

# 需要導入模塊: from pyramid import request [as 別名]
# 或者: from pyramid.request import Request [as 別名]
def openapi_view(view: View, info: ViewDeriverInfo) -> View:
    """View deriver that takes care of request/response validation.

    If `openapi=True` is passed to `@view_config`, this decorator will:

    - validate request and submit results into request.openapi_validated
    - Only request is validated here. The response is validated inside a tween,
    so that other tweens can intercept the response, and only the final
    response is validated against the openapi spec.
    """
    if info.options.get("openapi"):

        def wrapper_view(context: Context, request: Request) -> Response:
            # Validate request and attach all findings for view to introspect
            request.environ["pyramid_openapi3.validate_response"] = True
            settings = request.registry.settings["pyramid_openapi3"]

            # Needed to support relative `servers` entries in `openapi.yaml`,
            # see https://github.com/p1c2u/openapi-core/issues/218.
            settings["request_validator"].base_url = request.application_url
            settings["response_validator"].base_url = request.application_url

            openapi_request = PyramidOpenAPIRequestFactory.create(request)
            request.openapi_validated = settings["request_validator"].validate(
                openapi_request
            )
            if request.openapi_validated.errors:
                raise RequestValidationError(errors=request.openapi_validated.errors)
            # Do the view
            return view(context, request)

        return wrapper_view
    return view 
開發者ID:Pylons,項目名稱:pyramid_openapi3,代碼行數:35,代碼來源:__init__.py

示例12: test_request_validation_error

# 需要導入模塊: from pyramid import request [as 別名]
# 或者: from pyramid.request import Request [as 別名]
def test_request_validation_error(self) -> None:
        """Request validation errors are rendered as 400 JSON responses."""
        self._add_view()
        # run request through router
        router = Router(self.config.registry)
        environ = {
            "wsgi.url_scheme": "http",
            "SERVER_NAME": "localhost",
            "SERVER_PORT": "8080",
            "REQUEST_METHOD": "GET",
            "PATH_INFO": "/foo",
            "HTTP_ACCEPT": "application/json",
        }
        start_response = DummyStartResponse()
        with self.assertLogs(level="WARNING") as cm:
            response = router(environ, start_response)

        self.assertEqual(start_response.status, "400 Bad Request")
        self.assertEqual(
            json.loads(response[0]),
            [
                {
                    "exception": "MissingRequiredParameter",
                    "message": "Missing required parameter: bar",
                    "field": "bar",
                }
            ],
        )
        self.assertEqual(
            cm.output, ["WARNING:pyramid_openapi3:Missing required parameter: bar"]
        ) 
開發者ID:Pylons,項目名稱:pyramid_openapi3,代碼行數:33,代碼來源:test_validation.py

示例13: details

# 需要導入模塊: from pyramid import request [as 別名]
# 或者: from pyramid.request import Request [as 別名]
def details(request: Request):
    package_name = request.matchdict.get('package_name')
    if not package_name:
        raise x.HTTPNotFound()

    return {
        'package_name': package_name
    }


# /project/{package_name}/releases 
開發者ID:talkpython,項目名稱:data-driven-web-apps-with-pyramid-and-sqlalchemy,代碼行數:13,代碼來源:packages_controller.py

示例14: releases

# 需要導入模塊: from pyramid import request [as 別名]
# 或者: from pyramid.request import Request [as 別名]
def releases(request: Request):
    package_name = request.matchdict.get('package_name')
    if not package_name:
        raise x.HTTPNotFound()

    return {
        'package_name': package_name,
        'releases': []
    }


# /project/{package_name}/releases/{release_version} 
開發者ID:talkpython,項目名稱:data-driven-web-apps-with-pyramid-and-sqlalchemy,代碼行數:14,代碼來源:packages_controller.py

示例15: release_version

# 需要導入模塊: from pyramid import request [as 別名]
# 或者: from pyramid.request import Request [as 別名]
def release_version(request: Request):
    package_name = request.matchdict.get('package_name')
    release_ver = request.matchdict.get('release_version')
    if not package_name:
        raise x.HTTPNotFound()

    return {
        'package_name': package_name,
        'release_version': release_ver,
        'releases': []
    }


# /{num} 
開發者ID:talkpython,項目名稱:data-driven-web-apps-with-pyramid-and-sqlalchemy,代碼行數:16,代碼來源:packages_controller.py


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