本文整理匯總了Python中falcon.Request方法的典型用法代碼示例。如果您正苦於以下問題:Python falcon.Request方法的具體用法?Python falcon.Request怎麽用?Python falcon.Request使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類falcon
的用法示例。
在下文中一共展示了falcon.Request方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: test_python3_urllib_request_normalization
# 需要導入模塊: import falcon [as 別名]
# 或者: from falcon import Request [as 別名]
def test_python3_urllib_request_normalization(httpbin):
raw_request = urllib.request.Request(
httpbin.url + '/get',
headers={'Content-Type': 'application/json'},
)
request = normalize_request(raw_request)
assert request.path == '/get'
assert request.content_type == 'application/json'
assert request.url == httpbin.url + '/get'
assert request.method == 'get'
#
# Test tornado request object
#
示例2: test_falcon_request_normalization
# 需要導入模塊: import falcon [as 別名]
# 或者: from falcon import Request [as 別名]
def test_falcon_request_normalization(httpbin):
import falcon
from falcon.testing.helpers import create_environ
env = create_environ(
path='/put',
query_string='key=val',
host=httpbin.host,
port=httpbin.port,
headers={'Content-Type': 'application/json'},
body=b'{"key2": "val2"}',
method='PUT',
)
raw_request = falcon.Request(env)
request = normalize_request(raw_request)
assert request.path == '/put'
assert request.content_type == 'application/json'
assert request.url == httpbin.url + '/put?key=val'
assert request.method == 'put'
assert request.body == '{"key2": "val2"}'
示例3: test_werkzeug_request_normalization
# 需要導入模塊: import falcon [as 別名]
# 或者: from falcon import Request [as 別名]
def test_werkzeug_request_normalization(httpbin):
from werkzeug.test import create_environ
from werkzeug.wrappers import Request
env = create_environ(
path='/put',
base_url=httpbin.url,
query_string='key=val',
headers={'Content-Type': 'application/json'},
data=b'{"key2": "val2"}',
method='PUT',
)
raw_request = Request(env)
request = normalize_request(raw_request)
assert request.path == '/put'
assert request.content_type == 'application/json'
assert request.url == httpbin.url + '/put?key=val'
assert request.method == 'put'
assert request.data == {'key2': 'val2'}
示例4: on_get
# 需要導入模塊: import falcon [as 別名]
# 或者: from falcon import Request [as 別名]
def on_get(self, req, resp, handler=None, **kwargs):
"""Respond on GET HTTP request assuming resource retrieval flow.
This request handler assumes that GET requests are associated with
single resource instance retrieval. Thus default flow for such requests
is:
* Retrieve single resource instance of prepare its representation by
calling retrieve method handler.
Args:
req (falcon.Request): request object instance.
resp (falcon.Response): response object instance to be modified
handler (method): list method handler to be called. Defaults
to ``self.list``.
**kwargs: additional keyword arguments retrieved from url template.
"""
self.handle(
handler or self.retrieve, req, resp, **kwargs
)
示例5: on_delete
# 需要導入模塊: import falcon [as 別名]
# 或者: from falcon import Request [as 別名]
def on_delete(self, req, resp, handler=None, **kwargs):
"""Respond on DELETE HTTP request assuming resource deletion flow.
This request handler assumes that DELETE requests are associated with
resource deletion. Thus default flow for such requests is:
* Delete existing resource instance.
* Set response status code to ``202 Accepted``.
Args:
req (falcon.Request): request object instance.
resp (falcon.Response): response object instance to be modified
handler (method): deletion method handler to be called. Defaults
to ``self.delete``.
**kwargs: additional keyword arguments retrieved from url template.
"""
self.handle(
handler or self.delete, req, resp, **kwargs
)
resp.status = falcon.HTTP_ACCEPTED
示例6: on_put
# 需要導入模塊: import falcon [as 別名]
# 或者: from falcon import Request [as 別名]
def on_put(self, req, resp, handler=None, **kwargs):
"""Respond on PUT HTTP request assuming resource update flow.
This request handler assumes that PUT requests are associated with
resource update/modification. Thus default flow for such requests is:
* Modify existing resource instance and prepare its representation by
calling its update method handler.
* Set response status code to ``202 Accepted``.
Args:
req (falcon.Request): request object instance.
resp (falcon.Response): response object instance to be modified
handler (method): update method handler to be called. Defaults
to ``self.update``.
**kwargs: additional keyword arguments retrieved from url template.
"""
self.handle(
handler or self.update, req, resp, **kwargs
)
resp.status = falcon.HTTP_ACCEPTED
示例7: on_patch
# 需要導入模塊: import falcon [as 別名]
# 或者: from falcon import Request [as 別名]
def on_patch(self, req, resp, handler=None, **kwargs):
"""Respond on POST HTTP request assuming resource creation flow.
This request handler assumes that POST requests are associated with
resource creation. Thus default flow for such requests is:
* Create new resource instances and prepare their representation by
calling its bulk creation method handler.
* Set response status code to ``201 Created``.
**Note:** this handler does not set ``Location`` header by default as
it would be valid only for single resource creation.
Args:
req (falcon.Request): request object instance.
resp (falcon.Response): response object instance to be modified
handler (method): creation method handler to be called. Defaults
to ``self.create``.
**kwargs: additional keyword arguments retrieved from url template.
"""
self.handle(
handler or self.create_bulk, req, resp, **kwargs
)
resp.status = falcon.HTTP_CREATED
示例8: on_options
# 需要導入模塊: import falcon [as 別名]
# 或者: from falcon import Request [as 別名]
def on_options(self, req, resp, **kwargs):
"""Respond with JSON formatted resource description on OPTIONS request.
Args:
req (falcon.Request): Optional request object. Defaults to None.
resp (falcon.Response): Optional response object. Defaults to None.
kwargs (dict): Dictionary of values created by falcon from
resource uri template.
Returns:
None
.. versionchanged:: 0.2.0
Default ``OPTIONS`` responses include ``Allow`` header with list of
allowed HTTP methods.
"""
resp.set_header('Allow', ', '.join(self.allowed_methods()))
resp.body = json.dumps(self.describe(req, resp))
resp.content_type = 'application/json'
示例9: _get_client_address
# 需要導入模塊: import falcon [as 別名]
# 或者: from falcon import Request [as 別名]
def _get_client_address(self, req):
"""Get address from ``X-Forwarded-For`` header or use remote address.
Remote address is used if the ``X-Forwarded-For`` header is not
available. Note that this may not be safe to depend on both without
proper authorization backend.
Args:
req (falcon.Request): falcon.Request object.
Returns:
str: client address.
"""
try:
forwarded_for = req.get_header('X-Forwarded-For', True)
return forwarded_for.split(',')[0].strip()
except (KeyError, HTTPMissingHeader):
return (
req.env.get('REMOTE_ADDR') if self.remote_address_fallback
else None
)
示例10: _retrieve_header
# 需要導入模塊: import falcon [as 別名]
# 或者: from falcon import Request [as 別名]
def _retrieve_header(response, header):
""" Little compatibility utility for response.get_header() method.
response.get_header() was introduced in falcon 1.0 but we want to retrieve
response header values in al versions in consitent manner.
Args:
response (falcon.Request): request object instance
header (str): case-insensitive header name
"""
try:
return response.get_header(header)
except AttributeError:
# compat: on falcon<1.0 there is not get_header() method so we must
# access _headers dictionary directly
# note: _headers dictionary stores headers with lower-case names but
# get_header is case-insensitive so make make it lowercase to
# ensure consistency acros versions.
return response._headers[header.lower()]
示例11: test_resource_meta
# 需要導入模塊: import falcon [as 別名]
# 或者: from falcon import Request [as 別名]
def test_resource_meta(req, resp):
"""
Test if meta output part on resource GET has a desired structure
Args:
req (falcon.Request): request instance object provided by ``req``
pytest fixture
resp (falcon.Response): responce instance provided by ``resp`` pytest
fixture
"""
resource = TestResource()
resource.on_get(req, resp)
body = json.loads(resp.body)
assert 'meta' in body
assert 'params' in body['meta']
示例12: test_required_params
# 需要導入模塊: import falcon [as 別名]
# 或者: from falcon import Request [as 別名]
def test_required_params(req, resp):
"""
Test that when params are missing then specific falcon exception is raised
and thus proper status code will be returned.
Args:
req (falcon.Request): request instance object provided by ``req``
pytest fixture
resp (falcon.Response): responce instance provided by ``resp`` pytest
fixture
"""
class ParametrizedResource(TestResource):
foo = StringParam(details="required foo!", required=True)
resource = ParametrizedResource()
with pytest.raises(errors.HTTPMissingParam):
resource.on_get(req, resp)
param_req = copy.copy(req)
param_req.params['foo'] = 'bar'
resource.on_get(req, resp)
assert resp.status == falcon.HTTP_OK
示例13: test_describe
# 需要導入模塊: import falcon [as 別名]
# 或者: from falcon import Request [as 別名]
def test_describe(req, resp):
"""
Test if output of resource.description() has desired form.
Args:
req (falcon.Request): request instance object provided by ``req``
pytest fixture
resp (falcon.Response): responce instance provided by ``resp`` pytest
fixture
"""
# default description keys
resource = Resource()
description = resource.describe(req, resp)
assert 'path' in description
assert 'name' in description
assert 'details' in description
assert 'params' in description
assert 'methods' in description
# test extending of description through kwargs
assert 'foo' not in description
description = resource.describe(req, resp, foo='bar')
assert 'foo' in description
assert description['foo'] == 'bar'
示例14: test_whole_serializer_validation_as_hhtp_bad_request
# 需要導入模塊: import falcon [as 別名]
# 或者: from falcon import Request [as 別名]
def test_whole_serializer_validation_as_hhtp_bad_request(req):
class TestSerializer(BaseSerializer):
one = StringField("one different than two")
two = StringField("two different than one")
def validate(self, object_dict, partial=False):
super().validate(object_dict, partial)
# possible use case: kind of uniqueness relationship
if object_dict['one'] == object_dict['two']:
raise ValidationError("one must be different than two")
class TestResource(Resource):
serializer = TestSerializer()
resource = TestResource()
env = create_environ(
body=json.dumps({'one': 'foo', 'two': 'foo'}),
headers={'Content-Type': 'application/json'},
)
with pytest.raises(errors.HTTPBadRequest):
resource.require_validated(Request(env))
示例15: test_require_representation_application_json
# 需要導入模塊: import falcon [as 別名]
# 或者: from falcon import Request [as 別名]
def test_require_representation_application_json():
resource = TestResource()
# simple application/json content type
env = create_environ(
body=json.dumps({'one': 'foo', 'two': 'foo'}),
headers={'Content-Type': 'application/json'},
)
representation = resource.require_representation(Request(env))
assert isinstance(representation, dict)
# application/json content type with charset param
env = create_environ(
body=json.dumps({'one': 'foo', 'two': 'foo'}),
headers={'Content-Type': 'application/json; charset=UTF-8'},
)
representation = resource.require_representation(Request(env))
assert isinstance(representation, dict)