Python falcon.API Examples
The following are 30
code examples of falcon.API().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
falcon
, or try the search function
.
Example #1
Source File: app.py From iris-relay with BSD 2-Clause "Simplified" License | 8 votes |
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')
Example #2
Source File: test_falcon.py From sentry-python with BSD 2-Clause "Simplified" License | 7 votes |
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"]}
Example #3
Source File: api.py From monasca-log-api with Apache License 2.0 | 6 votes |
def create_version_app(global_conf, **local_conf): """Creates Version application""" ctrl = versions.Versions() controllers = { '/': ctrl, # redirect http://host:port/ down to Version app # avoid conflicts with actual pipelines and 404 error '/version': ctrl, # list all the versions '/version/{version_id}': ctrl # display details of the version } wsgi_app = falcon.API( request_type=request.Request ) wsgi_app.req_options.strip_url_path_trailing_slash = True for route, ctrl in controllers.items(): wsgi_app.add_route(route, ctrl) return wsgi_app
Example #4
Source File: app.py From iris-relay with BSD 2-Clause "Simplified" License | 6 votes |
def on_get(self, req, resp): token = req.get_param('token', True) data = {} for key in self.data_keys: data[key] = req.get_param(key, True) if not self.validate_token(token, data): raise falcon.HTTPForbidden('Invalid token for these given values', '') endpoint = self.config['iris']['hook']['gmail_one_click'] try: result = self.iclient.post(endpoint, data) except MaxRetryError: logger.exception('Hitting iris-api failed for gmail oneclick') else: if result.status == 204: resp.status = falcon.HTTP_204 return else: logger.error('Unexpected status code from api %s for gmail oneclick', result.status) raise falcon.HTTPInternalServerError('Internal Server Error', 'Invalid response from API')
Example #5
Source File: test_falcon.py From sentry-python with BSD 2-Clause "Simplified" License | 6 votes |
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"
Example #6
Source File: test_falcon.py From sentry-python with BSD 2-Clause "Simplified" License | 6 votes |
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
Example #7
Source File: test_falcon.py From sentry-python with BSD 2-Clause "Simplified" License | 6 votes |
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
Example #8
Source File: core.py From swagger-ui-py with Apache License 2.0 | 6 votes |
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()
Example #9
Source File: test_falcon.py From sentry-python with BSD 2-Clause "Simplified" License | 6 votes |
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"] == ""
Example #10
Source File: test_falcon.py From sentry-python with BSD 2-Clause "Simplified" License | 6 votes |
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
Example #11
Source File: api.py From freezer-api with Apache License 2.0 | 6 votes |
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
Example #12
Source File: api.py From freezer-api with Apache License 2.0 | 6 votes |
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
Example #13
Source File: rest_service.py From model_server with Apache License 2.0 | 6 votes |
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
Example #14
Source File: api.py From monasca-log-api with Apache License 2.0 | 6 votes |
def create_api_app(global_conf, **local_conf): """Creates MainAPI application""" controllers = {} api_version = global_conf.get('api_version') if api_version == 'v2.0': controllers.update({ '/log/single': v2_logs.Logs() }) elif api_version == 'v3.0': controllers.update({ '/logs': v3_logs.Logs() }) wsgi_app = falcon.API( request_type=request.Request ) for route, ctrl in controllers.items(): wsgi_app.add_route(route, ctrl) error_handlers.register_error_handlers(wsgi_app) return wsgi_app
Example #15
Source File: falsy.py From falsy with MIT License | 6 votes |
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()))
Example #16
Source File: main.py From Practical-Network-Automation-Second-Edition with MIT License | 6 votes |
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
Example #17
Source File: test_validators.py From falcon-boilerplate with MIT License | 6 votes |
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
Example #18
Source File: api.py From cccatalog-api with MIT License | 6 votes |
def create_api(log=True): """ Create an instance of the Falcon API server. """ if log: root = logging.getLogger() root.setLevel(logging.DEBUG) handler = logging.StreamHandler(sys.stdout) handler.setLevel(logging.INFO) formatter = logging.Formatter( '%(asctime)s %(levelname)s %(filename)s:%(lineno)d - %(message)s' ) handler.setFormatter(formatter) root.addHandler(handler) _api = falcon.API() task_tracker = TaskTracker() task_resource = TaskResource(task_tracker) get_task_status = TaskStatus(task_tracker) _api.add_route('/task', task_resource) _api.add_route('/task/{task_id}', get_task_status) _api.add_route('/worker_finished', WorkerFinishedResource()) _api.add_route('/state', StateResource()) return _api
Example #19
Source File: server.py From cc-utils with Apache License 2.0 | 6 votes |
def webhook_dispatcher_app( cfg_set, whd_cfg: WebhookDispatcherConfig, ): app = falcon.API( middleware=[], ) app.add_route('/github-webhook', GithubWebhook( whd_cfg=whd_cfg, cfg_set=cfg_set, ), ) return app
Example #20
Source File: __init__.py From falcon-boilerplate with MIT License | 5 votes |
def get_routes(app: falcon.API): app.add_route("/", Root()) app.add_route("/hello/{name}", HelloName())
Example #21
Source File: routes.py From falcon-boilerplate with MIT License | 5 votes |
def setup(app: falcon.API): for routes in (root_routes, users_routes): routes(app)
Example #22
Source File: falcon_demo.py From spectree with Apache License 2.0 | 5 votes |
def on_get(self, req, resp, source, target): """ API summary description here: test information with `source` and `target` """ resp.media = {'msg': f'hello from {source} to {target}'}
Example #23
Source File: app.py From falcon-boilerplate with MIT License | 5 votes |
def create_app() -> falcon.API: mw = [] if settings.get_bool("CORS_ENABLED"): if crossorigin_available is False: raise ImportError( "'cors-enabled' set but falcon-crossorigin is not installed, " "you must install it first to use CORS headers" ) cors = CrossOrigin( allow_origins=settings.get("CORS_ALLOW_ORIGINS"), allow_methods=settings.get("CORS_ALLOW_METHODS"), allow_headers=settings.get("CORS_ALLOW_HEADERS"), allow_credentials=settings.get_bool("CORS_ALLOW_CREDENTIALS"), expose_headers=settings.get("CORS_EXPOSE_HEADERS"), max_age=settings.get_int("CORS_MAX_AGE"), ) mw.append(cors) app = falcon.API(middleware=mw) dump_kwargs = {"ensure_ascii": False, "sort_keys": True} kwargs = json.add_settings_to_kwargs({}) dump_kwargs.update(kwargs) json_handler = falcon.media.JSONHandler( dumps=partial(json.dumps, **dump_kwargs), loads=partial(json.loads, **kwargs), ) extra_handlers = { falcon.MEDIA_JSON: json_handler, } app.req_options.media_handlers.update(extra_handlers) app.resp_options.media_handlers.update(extra_handlers) app.add_error_handler(Exception, error_handler) setup_routes(app) return app
Example #24
Source File: run.py From falcon-boilerplate with MIT License | 5 votes |
def init_app() -> falcon.API: configure() return create_app()
Example #25
Source File: remote_airflow.py From paperboy with Apache License 2.0 | 5 votes |
def start(self): """Start the whole thing""" self.port = os.environ.get('PORT', self.port) options = { 'bind': '0.0.0.0:{}'.format(self.port), 'workers': self.workers } def from_base(url): return urljoin(self.baseurl, url) api = falcon.API() remote = RemoteAirflowResource() status = RemoteAirflowStatusResource() api.add_route(from_base('remote'), remote) api.add_route(from_base('status'), status) ########## port = 8081 options = { 'bind': '0.0.0.0:{}'.format(port), 'workers': 1 } logging.debug('Running on port:{}'.format(port)) FalconDeploy(api, options).run()
Example #26
Source File: test_cors.py From paperboy with Apache License 2.0 | 5 votes |
def simulate_cors_api(self, cors, route='/'): self.api = falcon.API(middleware=[cors.middleware]) self.api.add_route(route, self.resource)
Example #27
Source File: api.py From monasca-log-api with Apache License 2.0 | 5 votes |
def create_healthcheck_app(global_conf, **local_conf): """Creates Healthcheck application""" ctrl = healthchecks.HealthChecks() controllers = { '/': ctrl } wsgi_app = falcon.API( request_type=request.Request ) for route, ctrl in controllers.items(): wsgi_app.add_route(route, ctrl) return wsgi_app
Example #28
Source File: main.py From Practical-Network-Automation-Second-Edition with MIT License | 5 votes |
def on_post(self,req,resp): # Handles POST Request print("In post") data=req.bounded_stream.read() try: bot_id=json.loads(data)["event"]["bot_id"] if bot_id=="BECJ82A3V": print("Ignore message from same bot") resp.status=falcon.HTTP_200 resp.body="" return except: print("Life goes on. . .") try: # Aythenticating end point to Slack data=json.loads(data)["challenge"] # Default status resp.status=falcon.HTTP_200 # Send challenge string back as response resp.body=data except: # URL already verified resp.status=falcon.HTTP_200 resp.body="" print(data) data=json.loads(data) #Get the channel and data information channel=data["event"]["channel"] text=data["event"]["text"] # Authenticate Agent to access Slack endpoint token="xoxp-xxxxxx" # Set parameters print(type(data)) print(text) set_data(channel,token,resp) # Proceess request and connect to slack channel channel_connect(text) return # falcon.API instance , callable from gunicorn
Example #29
Source File: __init__.py From certidude with MIT License | 5 votes |
def __init__(self): app = falcon.API(middleware=NormalizeMiddleware()) app.req_options.auto_parse_form_urlencoded = True self.attach(app) # Set up log handlers log_handlers = [] if config.LOGGING_BACKEND == "sql": from certidude.mysqllog import LogHandler from certidude.api.log import LogResource uri = config.cp.get("logging", "database") log_handlers.append(LogHandler(uri)) elif config.LOGGING_BACKEND == "syslog": from logging.handlers import SysLogHandler log_handlers.append(SysLogHandler()) # Browsing syslog via HTTP is obviously not possible out of the box elif config.LOGGING_BACKEND: raise ValueError("Invalid logging.backend = %s" % config.LOGGING_BACKEND) from certidude.push import EventSourceLogHandler log_handlers.append(EventSourceLogHandler()) for j in logging.Logger.manager.loggerDict.values(): if isinstance(j, logging.Logger): # PlaceHolder is what? if j.name.startswith("certidude."): j.setLevel(logging.DEBUG) for handler in log_handlers: j.addHandler(handler) self.server = make_server("127.0.1.1", self.PORT, app, WSGIServer) setproctitle("certidude: %s" % self.NAME)
Example #30
Source File: falcon_test.py From falcon-apispec with MIT License | 5 votes |
def test_resource_with_metadata(self, app, spec_factory): class HelloResource: """Greeting API. --- x-extension: global metadata """ hello_resource = HelloResource() app.add_route("/hi", hello_resource) spec = spec_factory(app) spec.path(resource=hello_resource) assert spec._paths["/hi"]["x-extension"] == "global metadata"