本文整理匯總了Python中falcon.HTTPBadRequest方法的典型用法代碼示例。如果您正苦於以下問題:Python falcon.HTTPBadRequest方法的具體用法?Python falcon.HTTPBadRequest怎麽用?Python falcon.HTTPBadRequest使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類falcon
的用法示例。
在下文中一共展示了falcon.HTTPBadRequest方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: on_put
# 需要導入模塊: import falcon [as 別名]
# 或者: from falcon import HTTPBadRequest [as 別名]
def on_put(self, req, resp):
try:
username, mail, created, expires, profile = self.manager.consume(req.get_param("token", required=True))
except RelationalMixin.DoesNotExist:
raise falcon.HTTPForbidden("Forbidden", "No such token or token expired")
body = req.stream.read(req.content_length)
header, _, der_bytes = pem.unarmor(body)
csr = CertificationRequest.load(der_bytes)
common_name = csr["certification_request_info"]["subject"].native["common_name"]
if not common_name.startswith(username + "@"):
raise falcon.HTTPBadRequest("Bad requst", "Invalid common name %s" % common_name)
try:
_, resp.body = self.authority._sign(csr, body, profile=config.PROFILES.get(profile),
overwrite=config.TOKEN_OVERWRITE_PERMITTED)
resp.set_header("Content-Type", "application/x-pem-file")
logger.info("Autosigned %s as proven by token ownership", common_name)
except FileExistsError:
logger.info("Won't autosign duplicate %s", common_name)
raise falcon.HTTPConflict(
"Certificate with such common name (CN) already exists",
"Will not overwrite existing certificate signing request, explicitly delete existing one and try again")
示例2: on_post
# 需要導入模塊: import falcon [as 別名]
# 或者: from falcon import HTTPBadRequest [as 別名]
def on_post(self, req, resp):
"""
Accept twilio POST that has message delivery status, and pass it
to iris-api
"""
try:
re = self.iclient.post(self.endpoint, req.context['body'].decode('utf-8'), raw=True)
except MaxRetryError:
logger.exception('Failed posting data to iris-api')
raise falcon.HTTPInternalServerError('Internal Server Error', 'API call failed')
if re.status != 204:
logger.error('Invalid response from API for delivery status update: %s', re.status)
raise falcon.HTTPBadRequest('Likely bad params passed', 'Invalid response from API')
resp.status = falcon.HTTP_204
示例3: test_bad_request_not_captured
# 需要導入模塊: import falcon [as 別名]
# 或者: from falcon import HTTPBadRequest [as 別名]
def test_bad_request_not_captured(sentry_init, capture_events):
sentry_init(integrations=[FalconIntegration()])
events = capture_events()
app = falcon.API()
class Resource:
def on_get(self, req, resp):
raise falcon.HTTPBadRequest()
app.add_route("/", Resource())
client = falcon.testing.TestClient(app)
client.simulate_get("/")
assert not events
示例4: process_request
# 需要導入模塊: import falcon [as 別名]
# 或者: from falcon import HTTPBadRequest [as 別名]
def process_request(self, req, resp, **kwargs):
if 'multipart/form-data' not in (req.content_type or ''):
return
# This must be done to avoid a bug in cgi.FieldStorage.
req.env.setdefault('QUERY_STRING', '')
# To avoid all stream consumption problem which occurs in falcon 1.0.0
# or above.
stream = (req.stream.stream if hasattr(req.stream, 'stream') else
req.stream)
try:
form = self.parse(stream=stream, environ=req.env)
except ValueError as e: # Invalid boundary?
raise falcon.HTTPBadRequest('Error parsing file', str(e))
for key in form:
# TODO: put files in req.files instead when #418 get merged.
req._params[key] = self.parse_field(form[key])
示例5: on_get
# 需要導入模塊: import falcon [as 別名]
# 或者: from falcon import HTTPBadRequest [as 別名]
def on_get(self, req, resp, model_name):
try:
model = get_model(model_name)
output = {
'dep_types': get_dep_types(model),
'ent_types': get_ent_types(model),
'pos_types': get_pos_types(model)
}
resp.body = json.dumps(output, sort_keys=True, indent=2)
resp.content_type = 'text/string'
resp.append_header('Access-Control-Allow-Origin', "*")
resp.status = falcon.HTTP_200
except Exception as e:
raise falcon.HTTPBadRequest(
'Schema construction failed',
'{}'.format(e))
示例6: on_post
# 需要導入模塊: import falcon [as 別名]
# 或者: from falcon import HTTPBadRequest [as 別名]
def on_post(self, req, resp):
req_body = req.bounded_stream.read()
json_data = json.loads(req_body.decode('utf8'))
text = json_data.get('text')
model_name = json_data.get('model', 'en')
collapse_punctuation = json_data.get('collapse_punctuation', True)
collapse_phrases = json_data.get('collapse_phrases', True)
try:
model = get_model(model_name)
parse = Parse(model, text, collapse_punctuation, collapse_phrases)
resp.body = json.dumps(parse.to_json(), sort_keys=True, indent=2)
resp.content_type = 'text/string'
resp.append_header('Access-Control-Allow-Origin', "*")
resp.status = falcon.HTTP_200
except Exception as e:
raise falcon.HTTPBadRequest(
'Dependency parsing failed',
'{}'.format(e))
示例7: identify
# 需要導入模塊: import falcon [as 別名]
# 或者: from falcon import HTTPBadRequest [as 別名]
def identify(self, req, resp, resource, uri_kwargs):
"""Identify user using Authenticate header with Token auth."""
header = req.get_header('Authorization', False)
auth = header.split(' ') if header else None
if auth is None or auth[0].lower() != 'token':
return None
if len(auth) != 2:
raise HTTPBadRequest(
"Invalid Authorization header",
"The Authorization header for Token auth should be in form:\n"
"Authorization: Token <token_value>"
)
return auth[1]
示例8: guarded_session
# 需要導入模塊: import falcon [as 別名]
# 或者: from falcon import HTTPBadRequest [as 別名]
def guarded_session():
'''
Context manager that will automatically close session on exceptions
'''
try:
session = Session()
yield session
except IrisValidationException as e:
session.close()
raise HTTPBadRequest('Validation error', str(e))
except (HTTPForbidden, HTTPUnauthorized, HTTPNotFound, HTTPBadRequest):
session.close()
raise
except Exception:
session.close()
logger.exception('SERVER ERROR')
raise
示例9: test_parse_invalid_body
# 需要導入模塊: import falcon [as 別名]
# 或者: from falcon import HTTPBadRequest [as 別名]
def test_parse_invalid_body():
from iris.webhooks.grafana import grafana
grafana_webhook = grafana()
fake_post = {
"evalMatches": [{
"value": 100,
"metric": "High value",
"tags": "",
}, {
"value": 200,
"metric": "Higher Value",
"tags": "",
}],
"imageUrl": "http://grafana.org/assets/img/blog/mixed_styles.png",
"message": "Someone is testing the alert notification within grafana.",
"ruleId": 0,
"ruleName": "Test notification",
"ruleUrl": "https://grafana.org/",
"title": "[Alerting] Test notification"
}
with pytest.raises(HTTPBadRequest):
grafana_webhook.validate_post(fake_post)
示例10: on_post
# 需要導入模塊: import falcon [as 別名]
# 或者: from falcon import HTTPBadRequest [as 別名]
def on_post(req, resp, team):
"""Update or create the secret key that grants public access to team's
oncall calendar for the logged-in user.
"""
challenger = req.context['user']
if not check_ical_team(team, challenger):
raise HTTPBadRequest(
'Invalid team name',
'Team "%s" does not exist or is inactive' % team,
)
key = generate_ical_key()
update_ical_key(challenger, team, 'team', key)
resp.status = HTTP_201
resp.body = key
resp.set_header('Content-Type', 'text/plain')
示例11: read_json_msg_body
# 需要導入模塊: import falcon [as 別名]
# 或者: from falcon import HTTPBadRequest [as 別名]
def read_json_msg_body(req):
"""Read the json_msg from the http request body and return them as JSON.
:param req: HTTP request object.
:return: Returns the metrics as a JSON object.
:raises falcon.HTTPBadRequest:
"""
try:
msg = req.stream.read()
json_msg = rest_utils.from_json(msg)
return json_msg
except rest_utils.exceptions.DataConversionException as ex:
LOG.debug(ex)
raise falcon.HTTPBadRequest('Bad request',
'Request body is not valid JSON')
except ValueError as ex:
LOG.debug(ex)
raise falcon.HTTPBadRequest('Bad request',
'Request body is not valid JSON')
示例12: validate_query_dimensions
# 需要導入模塊: import falcon [as 別名]
# 或者: from falcon import HTTPBadRequest [as 別名]
def validate_query_dimensions(dimensions):
"""Validates the query param dimensions.
:param dimensions: Query param dimensions.
:raises falcon.HTTPBadRequest: If dimensions are not valid.
"""
try:
for key, value in dimensions.items():
if key.startswith('_'):
raise Exception("Dimension key {} may not start with '_'".format(key))
metric_validation.validate_dimension_key(key)
if value:
if '|' in value:
values = value.split('|')
for v in values:
metric_validation.validate_dimension_value(key, v)
else:
metric_validation.validate_dimension_value(key, value)
except Exception as ex:
LOG.debug(ex)
raise HTTPUnprocessableEntityError('Unprocessable Entity', str(ex))
示例13: read_json_msg_body
# 需要導入模塊: import falcon [as 別名]
# 或者: from falcon import HTTPBadRequest [as 別名]
def read_json_msg_body(req):
"""Read the json_msg from the http request body and return them as JSON.
:param req: HTTP request object.
:return: Returns the metrics as a JSON object.
:raises falcon.HTTPBadRequest:
"""
try:
body = req.media
if body is not None:
return body
else:
raise falcon.HTTPBadRequest('Bad request',
'Request body is Empty')
except rest_utils.exceptions.DataConversionException as ex:
LOG.debug(ex)
raise falcon.HTTPBadRequest('Bad request',
'Request body is not valid JSON')
except ValueError as ex:
LOG.debug(ex)
raise falcon.HTTPBadRequest('Bad request',
'Request body is not valid JSON')
示例14: verbosity
# 需要導入模塊: import falcon [as 別名]
# 或者: from falcon import HTTPBadRequest [as 別名]
def verbosity(self, req):
"""Process the verbosity parameter
:param req: the Falcon request object
Valid values range from 0 (none) to 5 (maximum verbosity)
"""
try:
verbosity = req.get_param_as_int(
'verbosity', required=False, min=0, max=MAX_VERBOSITY
)
if verbosity is not None:
# if not set, retains the context default value.
req.context.verbosity = verbosity
except falcon.HTTPBadRequest as hbr:
LOG.exception(hbr)
raise ApiError(
title="Invalid verbosity parameter",
description=("If specified, verbosity parameter should be a "
"value from 0 to {}".format(MAX_VERBOSITY)),
status=falcon.HTTP_400
)
示例15: on_post
# 需要導入模塊: import falcon [as 別名]
# 或者: from falcon import HTTPBadRequest [as 別名]
def on_post(self, req, resp, cn):
namespace = ("user.%s." % self.namespace).encode("ascii")
try:
path, buf, cert, signed, expires = self.authority.get_signed(cn)
except IOError:
raise falcon.HTTPNotFound()
else:
for key in req.params:
if not re.match("[a-z0-9_\.]+$", key):
raise falcon.HTTPBadRequest("Invalid key %s" % key)
valid = set()
modified = False
for key, value in req.params.items():
identifier = ("user.%s.%s" % (self.namespace, key)).encode("ascii")
try:
if getxattr(path, identifier).decode("utf-8") != value:
modified = True
except OSError: # no such attribute
pass
setxattr(path, identifier, value.encode("utf-8"))
valid.add(identifier)
for key in listxattr(path):
if not key.startswith(namespace):
continue
if key not in valid:
modified = True
removexattr(path, key)
if modified:
push.publish("attribute-update", cn)