当前位置: 首页>>代码示例>>Python>>正文


Python httpexceptions.HTTPBadRequest方法代码示例

本文整理汇总了Python中pyramid.httpexceptions.HTTPBadRequest方法的典型用法代码示例。如果您正苦于以下问题:Python httpexceptions.HTTPBadRequest方法的具体用法?Python httpexceptions.HTTPBadRequest怎么用?Python httpexceptions.HTTPBadRequest使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在pyramid.httpexceptions的用法示例。


在下文中一共展示了httpexceptions.HTTPBadRequest方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_view_raises_valid_http_exception

# 需要导入模块: from pyramid import httpexceptions [as 别名]
# 或者: from pyramid.httpexceptions import HTTPBadRequest [as 别名]
def test_view_raises_valid_http_exception(self) -> None:
        """Test View raises HTTPException.

        Example view raises a defined response code.
        """
        from pyramid.httpexceptions import HTTPBadRequest

        def view_func(*args):
            raise HTTPBadRequest("bad foo request")

        self._add_view(view_func)
        view = self._get_view()
        request = self._get_request(params={"bar": "1"})
        with self.assertRaises(HTTPBadRequest) as cm:
            view(None, request)
        response = cm.exception
        # not enough of pyramid has been set up so we need to render the
        # exception response ourselves.
        response.prepare({"HTTP_ACCEPT": "application/json"})
        self.assertIn("bad foo request", response.json["message"]) 
开发者ID:Pylons,项目名称:pyramid_openapi3,代码行数:22,代码来源:test_validation.py

示例2: test_bad_request_not_captured

# 需要导入模块: from pyramid import httpexceptions [as 别名]
# 或者: from pyramid.httpexceptions import HTTPBadRequest [as 别名]
def test_bad_request_not_captured(
    sentry_init, pyramid_config, capture_events, route, get_client
):
    import pyramid.httpexceptions as exc

    sentry_init(integrations=[PyramidIntegration()])
    events = capture_events()

    @route("/")
    def index(request):
        raise exc.HTTPBadRequest()

    def errorhandler(exc, request):
        return Response("bad request")

    pyramid_config.add_view(errorhandler, context=exc.HTTPBadRequest)

    client = get_client()
    client.get("/")

    assert not events 
开发者ID:getsentry,项目名称:sentry-python,代码行数:23,代码来源:test_pyramid.py

示例3: validate

# 需要导入模块: from pyramid import httpexceptions [as 别名]
# 或者: from pyramid.httpexceptions import HTTPBadRequest [as 别名]
def validate(data, schema):
    """Validate data against a JSON schema.

    This is a helper function used by :py:class:`JsonSchemaValidationMixin`
    to validate data against a JSON schema. If validation fails this function
    will raise a :py:class:`pyramid.httpexceptions.HTTPBadRequest` exception
    describing the validation error.

    :raises pyramid.httpexceptions.HTTPBadRequest: if validation fails this
        exception is raised to abort any further processing.
    """
    try:
        jsonschema.validate(data, schema,
            format_checker=jsonschema.draft4_format_checker)
    except jsonschema.ValidationError as e:
        error = {
            '.'.join(str(p) for p in e.path): e.message
        }
        response = JSONValidationError(json=error)
        response.validation_error = e
        raise response 
开发者ID:wichert,项目名称:rest_toolkit,代码行数:23,代码来源:jsonschema.py

示例4: validate

# 需要导入模块: from pyramid import httpexceptions [as 别名]
# 或者: from pyramid.httpexceptions import HTTPBadRequest [as 别名]
def validate(data, schema):
    """Validate data against a Colander schema class.

    This is a helper function used by :py:class:`ColanderSchemaValidationMixin`
    to validate data against a Colander schema. If validation fails this function
    will raise a :py:class:`pyramid.httpexceptions.HTTPBadRequest` exception
    describing the validation error.

    :raises pyramid.httpexceptions.HTTPBadRequest: if validation fails this
        exception is raised to abort any further processing.
    """
    schema_instance = schema()
    try:
        schema_instance.deserialize(data)
    except colander.Invalid as e:
        raise HTTPBadRequest(e.msg) 
开发者ID:wichert,项目名称:rest_toolkit,代码行数:18,代码来源:colander.py

示例5: __init__

# 需要导入模块: from pyramid import httpexceptions [as 别名]
# 或者: from pyramid.httpexceptions import HTTPBadRequest [as 别名]
def __init__(self, request):
        raise HTTPBadRequest(json={'foo': 'bar'}) 
开发者ID:wichert,项目名称:rest_toolkit,代码行数:4,代码来源:resource_error.py

示例6: test_it_rejects_invalid_or_missing_urls

# 需要导入模块: from pyramid import httpexceptions [as 别名]
# 或者: from pyramid.httpexceptions import HTTPBadRequest [as 别名]
def test_it_rejects_invalid_or_missing_urls(self):
        invalid_urls = [
            None,
            # Unsupported protocols.
            "ftp://foo.bar",
            "doi:10.1.2/345",
            "file://foo.bar",
            # Malformed URLs.
            r"http://goo\[g",
        ]

        for url in invalid_urls:
            request = mock_request()
            request.GET["url"] = url

            with pytest.raises(httpexceptions.HTTPBadRequest):
                views.goto_url(request) 
开发者ID:hypothesis,项目名称:bouncer,代码行数:19,代码来源:views_test.py

示例7: depatisconnect_claims_handler_real

# 需要导入模块: from pyramid import httpexceptions [as 别名]
# 或者: from pyramid.httpexceptions import HTTPBadRequest [as 别名]
def depatisconnect_claims_handler_real(patent):
    try:
        claims = depatisconnect_claims(patent)

    except KeyError as ex:
        log.error('No details at DEPATISconnect: %s %s', type(ex), ex)
        raise HTTPNotFound(ex)

    except ValueError as ex:
        log.error('Fetching details from DEPATISconnect failed: %s %s', type(ex), ex)
        raise HTTPBadRequest(ex)

    except Exception as ex:
        log.error('Unknown error from DEPATISconnect: %s %s.', type(ex), ex)
        log.error(exception_traceback())
        raise HTTPBadRequest(ex)

    return claims 
开发者ID:ip-tools,项目名称:patzilla,代码行数:20,代码来源:dpma.py

示例8: depatisconnect_description_handler_real

# 需要导入模块: from pyramid import httpexceptions [as 别名]
# 或者: from pyramid.httpexceptions import HTTPBadRequest [as 别名]
def depatisconnect_description_handler_real(patent):
    try:
        description = depatisconnect_description(patent)
        if not description['xml']:
            raise KeyError('Description is empty')

    except KeyError as ex:
        log.error('No details at DEPATISconnect: %s %s', type(ex), ex)
        raise HTTPNotFound(ex)

    except ValueError as ex:
        log.error('Fetching details from DEPATISconnect failed: %s %s', type(ex), ex)
        raise HTTPBadRequest(ex)

    except Exception as ex:
        log.error('Unknown error from DEPATISconnect: %s %s.', type(ex), ex)
        log.error(exception_traceback())
        raise HTTPBadRequest(ex)

    return description 
开发者ID:ip-tools,项目名称:patzilla,代码行数:22,代码来源:dpma.py

示例9: depatisconnect_abstract_handler

# 需要导入模块: from pyramid import httpexceptions [as 别名]
# 或者: from pyramid.httpexceptions import HTTPBadRequest [as 别名]
def depatisconnect_abstract_handler(request):
    # TODO: use jsonified error responses
    patent = request.matchdict['patent']
    language = request.params.get('language')
    try:
        abstract = depatisconnect_abstracts(patent, language)

    except KeyError as ex:
        log.error('Problem fetching details of DEPATISconnect: %s %s', type(ex), ex)
        raise HTTPNotFound(ex)

    except ValueError as ex:
        log.error('Problem fetching details of DEPATISconnect: %s %s', type(ex), ex)
        raise HTTPBadRequest(ex)

    return abstract 
开发者ID:ip-tools,项目名称:patzilla,代码行数:18,代码来源:dpma.py

示例10: ificlaims_download_handler

# 需要导入模块: from pyramid import httpexceptions [as 别名]
# 或者: from pyramid.httpexceptions import HTTPBadRequest [as 别名]
def ificlaims_download_handler(request):
    """Download resources from IFI CLAIMS Direct"""

    resource = request.matchdict['resource']
    format   = request.matchdict['format'].lower()
    pretty   = asbool(request.params.get('pretty'))
    seq      = int(request.params.get('seq', 1))
    options = {'pretty': pretty, 'seq': seq}

    try:
        response = ificlaims_download(resource, format, options)

    except IFIClaimsException, ex:
        if type(ex) is IFIClaimsFormatException:
            raise HTTPNotFound(ex)
        else:
            raise HTTPBadRequest(ex) 
开发者ID:ip-tools,项目名称:patzilla,代码行数:19,代码来源:ificlaims.py

示例11: opaquelinks_verify_handler

# 需要导入模块: from pyramid import httpexceptions [as 别名]
# 或者: from pyramid.httpexceptions import HTTPBadRequest [as 别名]
def opaquelinks_verify_handler(request):
    """Verify an opaquelinks token"""

    token = token_payload(request)

    if not token:
        return HTTPBadRequest('Token missing')

    signer = request.registry.getUtility(ISigner)
    data, meta = signer.unsign(token)
    return data


# ------------------------------------------
#   utility functions
# ------------------------------------------ 
开发者ID:ip-tools,项目名称:patzilla,代码行数:18,代码来源:opaquelinks.py

示例12: newlunch

# 需要导入模块: from pyramid import httpexceptions [as 别名]
# 或者: from pyramid.httpexceptions import HTTPBadRequest [as 别名]
def newlunch(request):
    form = Form(request, schema=LunchSchema())
    if not form.validate:
        raise exc.HTTPBadRequest

    l = Lunch(
        submitter=request.POST.get('submitter', 'nobody'),
        food=request.POST.get('food', 'nothing'),
    )

    with transaction.manager:
        DBSession.add(l)

    raise exc.HTTPSeeOther('/') 
开发者ID:ryansb,项目名称:wut4lunch_demos,代码行数:16,代码来源:views.py

示例13: test_validation_error

# 需要导入模块: from pyramid import httpexceptions [as 别名]
# 或者: from pyramid.httpexceptions import HTTPBadRequest [as 别名]
def test_validation_error():
    resource = DummyResource()
    with pytest.raises(HTTPBadRequest):
        resource.validate({'email': 'john@example.com'}, partial=False) 
开发者ID:wichert,项目名称:rest_toolkit,代码行数:6,代码来源:test_colander.py

示例14: data_source

# 需要导入模块: from pyramid import httpexceptions [as 别名]
# 或者: from pyramid.httpexceptions import HTTPBadRequest [as 别名]
def data_source(request):
    try:
        hazardset_id = request.matchdict.get("hazardset")
        hazardset = (
            request.dbsession.query(HazardSet)
            .join(Layer)
            .filter(HazardSet.id == hazardset_id)
            .order_by(Layer.return_period)
            .options(contains_eager(HazardSet.layers))
            .one()
        )
    except:
        raise HTTPBadRequest(detail="incorrect value for parameter " '"hazardset"')

    return {"hazardset": hazardset} 
开发者ID:GFDRR,项目名称:thinkhazard,代码行数:17,代码来源:report.py

示例15: pdf_cover

# 需要导入模块: from pyramid import httpexceptions [as 别名]
# 或者: from pyramid.httpexceptions import HTTPBadRequest [as 别名]
def pdf_cover(request):
    try:
        division_code = request.matchdict.get("divisioncode")
    except:
        raise HTTPBadRequest(detail="incorrect value for parameter " '"divisioncode"')
    division = get_division(request, division_code)
    hazard_types = get_hazard_types(request, division_code)

    hazards_sorted = sorted(hazard_types, key=lambda a: a["hazardlevel"].order)

    hazard_categories = []
    for h in hazards_sorted:
        if h["hazardlevel"].mnemonic == _hazardlevel_nodata.mnemonic:
            continue
        hazard_categories.append(
            get_info_for_hazard_type(request, h["hazardtype"].mnemonic, division)
        )

    lon, lat = (
        request.dbsession.query(
            func.ST_X(ST_Centroid(AdministrativeDivision.geom)),
            func.ST_Y(ST_Centroid(AdministrativeDivision.geom)),
        )
        .filter(AdministrativeDivision.code == division_code)
        .first()
    )

    context = {
        "hazards": hazard_types,
        "hazards_sorted": sorted(hazard_types, key=lambda a: a["hazardlevel"].order),
        "parents": get_parents(division),
        "division": division,
        "division_lonlat": (lon, lat),
        "hazard_categories": hazard_categories,
        "date": datetime.datetime.now(),
    }

    return context 
开发者ID:GFDRR,项目名称:thinkhazard,代码行数:40,代码来源:pdf.py


注:本文中的pyramid.httpexceptions.HTTPBadRequest方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。