當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。