本文整理汇总了Python中falcon.API属性的典型用法代码示例。如果您正苦于以下问题:Python falcon.API属性的具体用法?Python falcon.API怎么用?Python falcon.API使用的例子?那么, 这里精选的属性代码示例或许可以为您提供帮助。您也可以进一步了解该属性所在类falcon
的用法示例。
在下文中一共展示了falcon.API属性的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: on_get
# 需要导入模块: import falcon [as 别名]
# 或者: from falcon import API [as 别名]
def on_get(self, req, resp, ical_key):
"""Access the oncall calendar identified by the key.
The response is in ical format and this url is intended to be
supplied to any calendar application that can subscribe to
calendars from the internet.
"""
try:
path = self.base_url + '/api/v0/ical/' + ical_key
if req.query_string:
path += '?%s' % req.query_string
result = self.oncall_client.get(path)
except MaxRetryError as ex:
logger.error(ex)
else:
if result.status_code == 200:
resp.status = falcon.HTTP_200
resp.content_type = result.headers['Content-Type']
resp.body = result.content
return
elif 400 <= result.status_code <= 499:
resp.status = falcon.HTTP_404
return
raise falcon.HTTPInternalServerError('Internal Server Error', 'Invalid response from API')
示例2: on_post
# 需要导入模块: import falcon [as 别名]
# 或者: from falcon import API [as 别名]
def on_post(self, req, resp):
"""
Accept twilio SMS webhook and forward to iris API
"""
try:
path = self.config['iris']['hook']['twilio_messages']
re = self.iclient.post(path, req.context['body'].decode('utf-8'), raw=True)
except MaxRetryError as e:
logger.error(e.reason)
self.return_twixml_message('Connection error to web hook.', resp)
return
if re.status != 200:
self.return_twixml_message(
'Got status code: %d, content: %s' % (re.status,
re.data[0:100]), resp)
return
else:
body = process_api_response(re.data)
self.return_twixml_message(body, resp)
return
示例3: test_errors
# 需要导入模块: import falcon [as 别名]
# 或者: from falcon import API [as 别名]
def test_errors(sentry_init, capture_exceptions, capture_events):
sentry_init(integrations=[FalconIntegration()], debug=True)
class ZeroDivisionErrorResource:
def on_get(self, req, resp):
1 / 0
app = falcon.API()
app.add_route("/", ZeroDivisionErrorResource())
exceptions = capture_exceptions()
events = capture_events()
client = falcon.testing.TestClient(app)
try:
client.simulate_get("/")
except ZeroDivisionError:
pass
(exc,) = exceptions
assert isinstance(exc, ZeroDivisionError)
(event,) = events
assert event["exception"]["values"][0]["mechanism"]["type"] == "falcon"
示例4: test_falcon_large_json_request
# 需要导入模块: import falcon [as 别名]
# 或者: from falcon import API [as 别名]
def test_falcon_large_json_request(sentry_init, capture_events):
sentry_init(integrations=[FalconIntegration()])
data = {"foo": {"bar": "a" * 2000}}
class Resource:
def on_post(self, req, resp):
assert req.media == data
sentry_sdk.capture_message("hi")
resp.media = "ok"
app = falcon.API()
app.add_route("/", Resource())
events = capture_events()
client = falcon.testing.TestClient(app)
response = client.simulate_post("/", json=data)
assert response.status == falcon.HTTP_200
(event,) = events
assert event["_meta"]["request"]["data"]["foo"]["bar"] == {
"": {"len": 2000, "rem": [["!limit", "x", 509, 512]]}
}
assert len(event["request"]["data"]["foo"]["bar"]) == 512
示例5: test_falcon_empty_json_request
# 需要导入模块: import falcon [as 别名]
# 或者: from falcon import API [as 别名]
def test_falcon_empty_json_request(sentry_init, capture_events, data):
sentry_init(integrations=[FalconIntegration()])
class Resource:
def on_post(self, req, resp):
assert req.media == data
sentry_sdk.capture_message("hi")
resp.media = "ok"
app = falcon.API()
app.add_route("/", Resource())
events = capture_events()
client = falcon.testing.TestClient(app)
response = client.simulate_post("/", json=data)
assert response.status == falcon.HTTP_200
(event,) = events
assert event["request"]["data"] == data
示例6: test_falcon_raw_data_request
# 需要导入模块: import falcon [as 别名]
# 或者: from falcon import API [as 别名]
def test_falcon_raw_data_request(sentry_init, capture_events):
sentry_init(integrations=[FalconIntegration()])
class Resource:
def on_post(self, req, resp):
sentry_sdk.capture_message("hi")
resp.media = "ok"
app = falcon.API()
app.add_route("/", Resource())
events = capture_events()
client = falcon.testing.TestClient(app)
response = client.simulate_post("/", body="hi")
assert response.status == falcon.HTTP_200
(event,) = events
assert event["request"]["headers"]["Content-Length"] == "2"
assert event["request"]["data"] == ""
示例7: test_500
# 需要导入模块: import falcon [as 别名]
# 或者: from falcon import API [as 别名]
def test_500(sentry_init, capture_events):
sentry_init(integrations=[FalconIntegration()])
app = falcon.API()
class Resource:
def on_get(self, req, resp):
1 / 0
app.add_route("/", Resource())
def http500_handler(ex, req, resp, params):
sentry_sdk.capture_exception(ex)
resp.media = {"message": "Sentry error: %s" % sentry_sdk.last_event_id()}
app.add_error_handler(Exception, http500_handler)
events = capture_events()
client = falcon.testing.TestClient(app)
response = client.simulate_get("/")
(event,) = events
assert response.json == {"message": "Sentry error: %s" % event["event_id"]}
示例8: test_bad_request_not_captured
# 需要导入模块: import falcon [as 别名]
# 或者: from falcon import API [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
示例9: build_app_v0
# 需要导入模块: import falcon [as 别名]
# 或者: from falcon import API [as 别名]
def build_app_v0():
"""Instantiate the root freezer-api app
Old versions of falcon (< 0.2.0) don't have a named 'middleware' argument.
This was introduced in version 0.2.0b1, so before that we need to instead
provide "before" hooks (request processing) and "after" hooks (response
processing).
:return: falcon WSGI app
"""
# injecting FreezerContext & hooks
before_hooks = utils.before_hooks() + [
middleware.RequireJSON().as_before_hook()]
after_hooks = [middleware.JSONTranslator().as_after_hook()]
# The signature of falcon.API() differs between versions, suppress pylint:
# pylint: disable=unexpected-keyword-arg
app = falcon.API(before=before_hooks, after=after_hooks)
app = configure_app(app)
return app
示例10: build_app_v1
# 需要导入模块: import falcon [as 别名]
# 或者: from falcon import API [as 别名]
def build_app_v1():
"""Building routes and forming the root freezer-api app
This uses the 'middleware' named argument to specify middleware for falcon
instead of the 'before' and 'after' hooks that were removed after 0.3.0
(both approaches were available for versions 0.2.0 - 0.3.0)
:return: falcon WSGI app
"""
# injecting FreezerContext & hooks
middleware_list = [utils.FuncMiddleware(hook) for hook in
utils.before_hooks()]
middleware_list.append(middleware.RequireJSON())
middleware_list.append(middleware.JSONTranslator())
# The signature of falcon.API() differs between versions, suppress pylint:
# pylint: disable=unexpected-keyword-arg
app = falcon.API(middleware=middleware_list)
# Set options to keep behavior compatible to pre-2.0.0 falcon
app.req_options.auto_parse_qs_csv = True
app.req_options.keep_blank_qs_values = False
app.req_options.strip_url_path_trailing_slash = True
app = configure_app(app)
return app
示例11: create_rest_api
# 需要导入模块: import falcon [as 别名]
# 或者: from falcon import API [as 别名]
def create_rest_api(models):
app = falcon.API()
get_model_status = GetModelStatus(models)
get_model_meta = GetModelMetadata(models)
predict = Predict(models)
app.add_route('/v1/models/{model_name}', get_model_status)
app.add_route('/v1/models/{model_name}/'
'versions/{requested_version}',
get_model_status)
app.add_route('/v1/models/{model_name}/metadata', get_model_meta)
app.add_route('/v1/models/{model_name}/'
'versions/{requested_version}/metadata',
get_model_meta)
app.add_route('/v1/models/{model_name}:predict', predict)
app.add_route('/v1/models/{model_name}/versions/'
'{requested_version}:predict',
predict)
return app
示例12: __init__
# 需要导入模块: import falcon [as 别名]
# 或者: from falcon import API [as 别名]
def __init__(self, app, app_type=None, config_path=None, config_url=None,
url_prefix='/api/doc', title='API doc', editor=False):
self._app = app
self._title = title
self._url_prefix = url_prefix.rstrip('/')
self._config_url = config_url
self._config_path = config_path
self._editor = editor
assert self._config_url or self._config_path, 'config_url or config_path is required!'
self._env = Environment(
loader=FileSystemLoader(str(CURRENT_DIR.joinpath('templates'))),
autoescape=select_autoescape(['html'])
)
if app_type and hasattr(self, '_{}_handler'.format(app_type)):
getattr(self, '_{}_handler'.format(app_type))()
else:
self._auto_match_handler()
示例13: __init__
# 需要导入模块: import falcon [as 别名]
# 或者: from falcon import API [as 别名]
def __init__(self, falcon_api=None,
static_path='static', static_dir='static', log_config=None):
if log_config is None:
self.log = JLog().setup().bind()
else:
self.log = JLog().setup(config=log_config).bind()
self.log.info(cc('falsy init', fore=77, styles=['italic', 'underlined', 'reverse']))
self.api = self.falcon_api = falcon_api or falcon.API()
self.static_path = static_path.strip('/')
self.static_dir = static_dir if os.path.isdir(static_dir) else '.'
self.api = CommonStaticMiddleware(self.falcon_api, static_dir=self.static_dir,
url_prefix=self.static_path)
self.log.info('common static middleware loaded\n\t{}'.format(
'url_prefix(static_path):' + reverse() + self.static_path + rreverse() +
', static_dir:' + reverse() + self.static_dir + rreverse()))
示例14: on_post
# 需要导入模块: import falcon [as 别名]
# 或者: from falcon import API [as 别名]
def on_post(self, req, resp):
data = req.bounded_stream.read()
try:
token = json.loads(data)["token"]
token = "$pbkdf2-sha256$29000$" + token
except:
print("key token is missing")
resp.body = "token 'key' is missing"
return
with open('token.txt', 'r') as f:
token_old = f.read()
if token == token_old:
resp.body = json.dumps("Hello John!")
return
else:
resp.body = json.dumps("Token does not exist")
return
# falcon.API instance , callable from gunicorn
示例15: test_both_schemas_validation_failure
# 需要导入模块: import falcon [as 别名]
# 或者: from falcon import API [as 别名]
def test_both_schemas_validation_failure():
with pytest.raises(HTTPError) as excinfo:
Resource().both_validated(GoodData(), BadData())
assert excinfo.value.title == falcon.HTTP_INTERNAL_SERVER_ERROR
assert excinfo.value.description == "Response data failed validation"
with pytest.raises(HTTPError) as excinfo:
Resource().both_validated(BadData(), GoodData())
msg = "Request data failed validation: data must contain ['message'] properties"
assert excinfo.value.title == falcon.HTTP_BAD_REQUEST
assert excinfo.value.description == msg
client = testing.TestClient(falcon.API())
client.app.add_route("/test", Resource())
result = client.simulate_put("/test", json=BadData.media)
assert result.status_code == 400