本文整理汇总了Python中falcon.HTTPUnsupportedMediaType方法的典型用法代码示例。如果您正苦于以下问题:Python falcon.HTTPUnsupportedMediaType方法的具体用法?Python falcon.HTTPUnsupportedMediaType怎么用?Python falcon.HTTPUnsupportedMediaType使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类falcon
的用法示例。
在下文中一共展示了falcon.HTTPUnsupportedMediaType方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: serialize
# 需要导入模块: import falcon [as 别名]
# 或者: from falcon import HTTPUnsupportedMediaType [as 别名]
def serialize(func):
"""
Falcon response serialization
"""
import falcon
def wrapped(instance, req, resp, **kwargs):
retval = func(instance, req, resp, **kwargs)
if not resp.body and not resp.location:
if not req.client_accepts("application/json"):
logger.debug("Client did not accept application/json")
raise falcon.HTTPUnsupportedMediaType(
"Client did not accept application/json")
resp.set_header("Cache-Control", "no-cache, no-store, must-revalidate")
resp.set_header("Pragma", "no-cache")
resp.set_header("Expires", "0")
resp.body = json.dumps(retval, cls=MyEncoder)
return wrapped
示例2: on_get
# 需要导入模块: import falcon [as 别名]
# 或者: from falcon import HTTPUnsupportedMediaType [as 别名]
def on_get(self, req, resp):
# Primarily offer DER encoded CRL as per RFC5280
# This is also what StrongSwan expects
if req.client_accepts("application/x-pkcs7-crl"):
resp.set_header("Content-Type", "application/x-pkcs7-crl")
resp.append_header(
"Content-Disposition",
("attachment; filename=%s.crl" % const.HOSTNAME))
# Convert PEM to DER
logger.debug("Serving revocation list (DER) to %s", req.context.get("remote_addr"))
resp.body = self.authority.export_crl(pem=False)
elif req.client_accepts("application/x-pem-file"):
resp.set_header("Content-Type", "application/x-pem-file")
resp.append_header(
"Content-Disposition",
("attachment; filename=%s-crl.pem" % const.HOSTNAME))
logger.debug("Serving revocation list (PEM) to %s", req.context.get("remote_addr"))
resp.body = self.authority.export_crl()
else:
logger.debug("Client %s asked revocation list in unsupported format" % req.context.get("remote_addr"))
raise falcon.HTTPUnsupportedMediaType(
"Client did not accept application/x-pkcs7-crl or application/x-pem-file")
示例3: serialize
# 需要导入模块: import falcon [as 别名]
# 或者: from falcon import HTTPUnsupportedMediaType [as 别名]
def serialize(func):
"""
Falcon response serialization
"""
def wrapped(instance, req, resp, **kwargs):
assert not req.get_param("unicode") or req.get_param("unicode") == u"✓", "Unicode sanity check failed"
resp.set_header("Cache-Control", "no-cache, no-store, must-revalidate");
resp.set_header("Pragma", "no-cache");
resp.set_header("Expires", "0");
r = func(instance, req, resp, **kwargs)
if not resp.body:
if not req.client_accepts_json:
raise falcon.HTTPUnsupportedMediaType(
'This API only supports the JSON media type.',
href='http://docs.examples.com/api/json')
resp.set_header('Content-Type', 'application/json')
resp.body = json.dumps(r, cls=MyEncoder)
return r
return wrapped
示例4: test_require_representation_unsupported_media_type
# 需要导入模块: import falcon [as 别名]
# 或者: from falcon import HTTPUnsupportedMediaType [as 别名]
def test_require_representation_unsupported_media_type():
resource = TestResource()
# invalid content type format
env = create_environ(
body=json.dumps({'one': 'foo', 'two': 'foo'}),
headers={'Content-Type': 'foo bar'},
)
with pytest.raises(falcon.HTTPUnsupportedMediaType):
resource.require_representation(Request(env))
# valid format but surely unsupported (RFC-1437)
env = create_environ(
body=json.dumps({'one': 'foo', 'two': 'foo'}),
headers={'Content-Type': 'matter-transport/sentient-life-form'},
)
with pytest.raises(falcon.HTTPUnsupportedMediaType):
resource.require_representation(Request(env))
示例5: whitelist_content_types
# 需要导入模块: import falcon [as 别名]
# 或者: from falcon import HTTPUnsupportedMediaType [as 别名]
def whitelist_content_types(*content_types):
def wrapper(func):
def wrapped(self, req, resp, *args, **kwargs):
for content_type in content_types:
if req.get_header("Content-Type") == content_type:
return func(self, req, resp, *args, **kwargs)
raise falcon.HTTPUnsupportedMediaType(
"This API call accepts only %s content type" % ", ".join(content_types))
return wrapped
return wrapper
示例6: on_get
# 需要导入模块: import falcon [as 别名]
# 或者: from falcon import HTTPUnsupportedMediaType [as 别名]
def on_get(self, req, resp, cn):
"""
Fetch certificate signing request as PEM
"""
try:
path, buf, _, submitted = self.authority.get_request(cn)
except errors.RequestDoesNotExist:
logger.warning("Failed to serve non-existant request %s to %s",
cn, req.context.get("remote_addr"))
raise falcon.HTTPNotFound()
resp.set_header("Content-Type", "application/pkcs10")
logger.debug("Signing request %s was downloaded by %s",
cn, req.context.get("remote_addr"))
preferred_type = req.client_prefers(("application/json", "application/x-pem-file"))
if preferred_type == "application/x-pem-file":
# For certidude client, curl scripts etc
resp.set_header("Content-Type", "application/x-pem-file")
resp.set_header("Content-Disposition", ("attachment; filename=%s.pem" % cn))
resp.body = buf
elif preferred_type == "application/json":
# For web interface events
resp.set_header("Content-Type", "application/json")
resp.set_header("Content-Disposition", ("attachment; filename=%s.json" % cn))
resp.body = json.dumps(dict(
submitted = submitted,
common_name = cn,
address = getxattr(path, "user.request.address").decode("ascii"), # TODO: move to authority.py
md5sum = hashlib.md5(buf).hexdigest(),
sha1sum = hashlib.sha1(buf).hexdigest(),
sha256sum = hashlib.sha256(buf).hexdigest(),
sha512sum = hashlib.sha512(buf).hexdigest()), cls=MyEncoder)
else:
raise falcon.HTTPUnsupportedMediaType(
"Client did not accept application/json or application/x-pem-file")
示例7: require_representation
# 需要导入模块: import falcon [as 别名]
# 或者: from falcon import HTTPUnsupportedMediaType [as 别名]
def require_representation(self, req):
"""Require raw representation dictionary from falcon request object.
This does not perform any field parsing or validation but only uses
allowed content-encoding handler to decode content body.
Note:
Currently only JSON is allowed as content type.
Args:
req (falcon.Request): request object
Returns:
dict: raw dictionary of representation supplied in request body
"""
try:
type_, subtype, _ = parse_mime_type(req.content_type)
content_type = '/'.join((type_, subtype))
except:
raise falcon.HTTPUnsupportedMediaType(
description="Invalid Content-Type header: {}".format(
req.content_type
)
)
if content_type == 'application/json':
body = req.stream.read()
return json.loads(body.decode('utf-8'))
else:
raise falcon.HTTPUnsupportedMediaType(
description="only JSON supported, got: {}".format(content_type)
)
示例8: validate_content_type
# 需要导入模块: import falcon [as 别名]
# 或者: from falcon import HTTPUnsupportedMediaType [as 别名]
def validate_content_type(req, allowed):
"""Validates content type.
Method validates request against correct
content type.
If content-type cannot be established (i.e. header is missing),
:py:class:`falcon.HTTPMissingHeader` is thrown.
If content-type is not **application/json** or **text/plain**,
:py:class:`falcon.HTTPUnsupportedMediaType` is thrown.
:param falcon.Request req: current request
:param iterable allowed: allowed content type
:exception: :py:class:`falcon.HTTPMissingHeader`
:exception: :py:class:`falcon.HTTPUnsupportedMediaType`
"""
content_type = req.content_type
LOG.debug('Content-Type is %s', content_type)
if content_type is None or len(content_type) == 0:
raise falcon.HTTPMissingHeader('Content-Type')
if content_type not in allowed:
sup_types = ', '.join(allowed)
details = ('Only [%s] are accepted as logs representations'
% str(sup_types))
raise falcon.HTTPUnsupportedMediaType(description=details)
示例9: on_get
# 需要导入模块: import falcon [as 别名]
# 或者: from falcon import HTTPUnsupportedMediaType [as 别名]
def on_get(self, req, resp, cn):
preferred_type = req.client_prefers(("application/json", "application/x-pem-file"))
try:
path, buf, cert, signed, expires = self.authority.get_signed(cn)
except EnvironmentError:
logger.warning("Failed to serve non-existant certificate %s to %s",
cn, req.context.get("remote_addr"))
raise falcon.HTTPNotFound()
if preferred_type == "application/x-pem-file":
resp.set_header("Content-Type", "application/x-pem-file")
resp.set_header("Content-Disposition", ("attachment; filename=%s.pem" % cn))
resp.body = buf
logger.debug("Served certificate %s to %s as application/x-pem-file",
cn, req.context.get("remote_addr"))
elif preferred_type == "application/json":
resp.set_header("Content-Type", "application/json")
resp.set_header("Content-Disposition", ("attachment; filename=%s.json" % cn))
try:
signer_username = getxattr(path, "user.signature.username").decode("ascii")
except IOError:
signer_username = None
attributes = {}
for key in listxattr(path):
if key.startswith(b"user.machine."):
attributes[key[13:].decode("ascii")] = getxattr(path, key).decode("ascii")
# TODO: dedup
resp.body = json.dumps(dict(
common_name = cn,
signer = signer_username,
serial = "%040x" % cert.serial_number,
organizational_unit = cert.subject.native.get("organizational_unit_name"),
signed = cert["tbs_certificate"]["validity"]["not_before"].native.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z",
expires = cert["tbs_certificate"]["validity"]["not_after"].native.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z",
sha256sum = hashlib.sha256(buf).hexdigest(),
attributes = attributes or None,
lease = None,
extensions = dict([
(e["extn_id"].native, e["extn_value"].native)
for e in cert["tbs_certificate"]["extensions"]
if e["extn_id"].native in ("extended_key_usage",)])
))
logger.debug("Served certificate %s to %s as application/json",
cn, req.context.get("remote_addr"))
else:
logger.debug("Client did not accept application/json or application/x-pem-file")
raise falcon.HTTPUnsupportedMediaType(
"Client did not accept application/json or application/x-pem-file")