本文整理匯總了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"])
示例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
示例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
示例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)
示例5: __init__
# 需要導入模塊: from pyramid import httpexceptions [as 別名]
# 或者: from pyramid.httpexceptions import HTTPBadRequest [as 別名]
def __init__(self, request):
raise HTTPBadRequest(json={'foo': 'bar'})
示例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)
示例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
示例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
示例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
示例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)
示例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
# ------------------------------------------
示例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('/')
示例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)
示例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}
示例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