当前位置: 首页>>代码示例>>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;未经允许,请勿转载。