def test_rest_with_validation_redirects(self): """ Fixing a bug: When schema validation fails, pecan can use an internal redirect (paste.recursive.ForwardRequestException) to send you to another controller to "handle" the display of error messages. Additionally, pecan overwrites the request method as GET. In some circumstances, RestController's special `_method` parameter prevents the redirected request from routing to the appropriate `error_handler` controller. """ class SampleSchema(formencode.Schema): name = formencode.validators.String() class UserController(RestController): @expose() def get_one(self, id): return "FORM VALIDATION FAILED" @expose( schema = SampleSchema(), error_handler = lambda: request.path ) def put(self, id): raise AssertionError, "Schema validation should fail." @expose( schema = SampleSchema(), error_handler = lambda: request.path ) def delete(self, id): raise AssertionError, "Schema validation should fail." class RootController(object): users = UserController() # create the app app = TestApp(make_app(RootController())) # create the app app = TestApp(make_app(RootController())) # test proper internal redirection r = app.post('/users/1?_method=put') assert r.status_int == 200 assert r.body == "FORM VALIDATION FAILED" r = app.post('/users/1?_method=delete') assert r.status_int == 200 assert r.body == "FORM VALIDATION FAILED"
def test_app_wrap(self): class RootController(object): pass wrapped_apps = [] def wrap(app): wrapped_apps.append(app) return app make_app(RootController(), wrap_app=wrap, debug=True) assert len(wrapped_apps) == 1
def setup_app(pecan_config=None, extra_hooks=None): # FIXME: Replace DBHook with a hooks.TransactionHook app_hooks = [hooks.ConfigHook(), hooks.DBHook(), hooks.NotifierHook(), hooks.TranslationHook()] if extra_hooks: app_hooks.extend(extra_hooks) if not pecan_config: pecan_config = get_pecan_config() pecan.configuration.set_config(dict(pecan_config), overwrite=True) # NOTE(sileht): pecan debug won't work in multi-process environment pecan_debug = CONF.api.pecan_debug if service.get_workers('api') != 1 and pecan_debug: pecan_debug = False LOG.warning(_LW('pecan_debug cannot be enabled, if workers is > 1, ' 'the value is overrided with False')) app = pecan.make_app( pecan_config.app.root, debug=pecan_debug, force_canonical=getattr(pecan_config.app, 'force_canonical', True), hooks=app_hooks, wrap_app=middleware.ParsableErrorMiddleware, guess_content_type_from_ext=False ) return app
def setup_app(pecan_config=None): # FIXME: Replace DBHook with a hooks.TransactionHook app_hooks = [hooks.ConfigHook(), hooks.DBHook(), hooks.NotifierHook(), hooks.TranslationHook()] pecan_config = pecan_config or { "app": { 'root': 'ceilometer.api.controllers.root.RootController', 'modules': ['ceilometer.api'], } } pecan.configuration.set_config(dict(pecan_config), overwrite=True) # NOTE(sileht): pecan debug won't work in multi-process environment pecan_debug = CONF.api.pecan_debug if CONF.api.workers and CONF.api.workers != 1 and pecan_debug: pecan_debug = False LOG.warning(_LW('pecan_debug cannot be enabled, if workers is > 1, ' 'the value is overrided with False')) app = pecan.make_app( pecan_config['app']['root'], debug=pecan_debug, hooks=app_hooks, wrap_app=middleware.ParsableErrorMiddleware, guess_content_type_from_ext=False ) return app
def test_x_forward_proto(self): class ChildController(object): @expose() def index(self): redirect('/testing') # pragma: nocover class RootController(object): @expose() def index(self): redirect('/testing') # pragma: nocover @expose() def testing(self): return 'it worked!' # pragma: nocover child = ChildController() app = TestApp(make_app(RootController(), debug=True)) res = app.get( '/child', extra_environ=dict(HTTP_X_FORWARDED_PROTO='https') ) # non-canonical url will redirect, so we won't get a 301 assert res.status_int == 302 # should add trailing / and changes location to https assert res.location == 'https://localhost/child/' assert res.request.environ['HTTP_X_FORWARDED_PROTO'] == 'https'
def test_secure_attribute(self): authorized = False class SubController(object): @expose() def index(self): return 'Hello from sub!' class RootController(object): @expose() def index(self): return 'Hello from root!' sub = secure(SubController(), lambda: authorized) app = TestApp(make_app(RootController())) response = app.get('/') assert response.status_int == 200 assert response.body == 'Hello from root!' response = app.get('/sub/', expect_errors=True) assert response.status_int == 401 authorized = True response = app.get('/sub/') assert response.status_int == 200 assert response.body == 'Hello from sub!'
def test_item_not_in_defaults(self): _stdout = StringIO() class RootController(object): @expose() def index(self): return 'Hello, World!' app = TestApp( make_app( RootController(), hooks=lambda: [ RequestViewerHook( config={'items': ['date']}, writer=_stdout ) ] ) ) response = app.get('/') out = _stdout.getvalue() assert response.status_int == 200 assert response.body == b_('Hello, World!') assert 'date' in out assert 'method' not in out assert 'status' not in out assert 'method' not in out assert 'params' not in out assert 'hooks' not in out assert '200 OK' not in out assert "['RequestViewerHook']" not in out assert '/' not in out
def test_basic_single_hook(self): run_hook = [] class RootController(object): @expose() def index(self): run_hook.append('inside') return 'Hello, World!' class SimpleHook(PecanHook): def on_route(self, state): run_hook.append('on_route') def before(self, state): run_hook.append('before') def after(self, state): run_hook.append('after') def on_error(self, state, e): run_hook.append('error') app = TestApp(make_app(RootController(), hooks=[SimpleHook()])) response = app.get('/') assert response.status_int == 200 assert response.body == b_('Hello, World!') assert len(run_hook) == 4 assert run_hook[0] == 'on_route' assert run_hook[1] == 'before' assert run_hook[2] == 'inside' assert run_hook[3] == 'after'
def test_on_error_response_hook(self): run_hook = [] class RootController(object): @expose() def causeerror(self): return [][1] class ErrorHook(PecanHook): def on_error(self, state, e): run_hook.append('error') r = Response() r.text = u_('on_error') return r app = TestApp(make_app(RootController(), hooks=[ ErrorHook() ])) response = app.get('/causeerror') assert len(run_hook) == 1 assert run_hook[0] == 'error' assert response.text == 'on_error'
def test_404_with_lookup(self): class LookupController(RestController): def __init__(self, _id): self._id = _id @expose() def get_all(self): return 'ID: %s' % self._id class ThingsController(RestController): @expose() def _lookup(self, _id, *remainder): return LookupController(_id), remainder class RootController(object): things = ThingsController() # create the app app = TestApp(make_app(RootController())) # these should 404 for path in ('/things', '/things/'): r = app.get(path, expect_errors=True) assert r.status_int == 404 r = app.get('/things/foo') assert r.status_int == 200 assert r.body == b_('ID: foo')
def test_get_with_var_args(self): class OthersController(object): @expose() def index(self, one, two, three): return 'NESTED: %s, %s, %s' % (one, two, three) class ThingsController(RestController): others = OthersController() @expose() def get_one(self, *args): return ', '.join(args) class RootController(object): things = ThingsController() # create the app app = TestApp(make_app(RootController())) # test get request r = app.get('/things/one/two/three') assert r.status_int == 200 assert r.body == b_('one, two, three') # test nested get request r = app.get('/things/one/two/three/others/') assert r.status_int == 200 assert r.body == b_('NESTED: one, two, three')
def test_custom_with_trailing_slash(self): class CustomController(RestController): _custom_actions = { 'detail': ['GET'], 'create': ['POST'], 'update': ['PUT'], 'remove': ['DELETE'], } @expose() def detail(self): return 'DETAIL' @expose() def create(self): return 'CREATE' @expose() def update(self, id): return id @expose() def remove(self, id): return id app = TestApp(make_app(CustomController())) r = app.get('/detail') assert r.status_int == 200 assert r.body == b_('DETAIL') r = app.get('/detail/') assert r.status_int == 200 assert r.body == b_('DETAIL') r = app.post('/create') assert r.status_int == 200 assert r.body == b_('CREATE') r = app.post('/create/') assert r.status_int == 200 assert r.body == b_('CREATE') r = app.put('/update/123') assert r.status_int == 200 assert r.body == b_('123') r = app.put('/update/123/') assert r.status_int == 200 assert r.body == b_('123') r = app.delete('/remove/456') assert r.status_int == 200 assert r.body == b_('456') r = app.delete('/remove/456/') assert r.status_int == 200 assert r.body == b_('456')
def setup_app(pecan_config=None, extra_hooks=None): app_hooks = [hooks.ConfigHook(), hooks.DBHook()] if extra_hooks: app_hooks.extend(extra_hooks) if not pecan_config: pecan_config = get_pecan_config() if pecan_config.app.enable_acl: app_hooks.append(acl.AdminAuthHook()) pecan.configuration.set_config(dict(pecan_config), overwrite=True) # TODO(deva): add middleware.ParsableErrorMiddleware from Ceilometer app = pecan.make_app( pecan_config.app.root, custom_renderers=dict(wsmejson=renderers.JSONRenderer), static_root=pecan_config.app.static_root, template_path=pecan_config.app.template_path, debug=CONF.debug, force_canonical=getattr(pecan_config.app, 'force_canonical', True), hooks=app_hooks, ) if pecan_config.app.enable_acl: return acl.install(app, cfg.CONF) return app
def setup_app(pecan_config=None, extra_hooks=None): storage_engine = storage.get_engine(cfg.CONF) # FIXME: Replace DBHook with a hooks.TransactionHook app_hooks = [hooks.ConfigHook(), hooks.DBHook( storage_engine, storage_engine.get_connection(cfg.CONF), ), hooks.PipelineHook(), hooks.TranslationHook()] if extra_hooks: app_hooks.extend(extra_hooks) if not pecan_config: pecan_config = get_pecan_config() pecan.configuration.set_config(dict(pecan_config), overwrite=True) app = pecan.make_app( pecan_config.app.root, static_root=pecan_config.app.static_root, template_path=pecan_config.app.template_path, debug=CONF.debug, force_canonical=getattr(pecan_config.app, 'force_canonical', True), hooks=app_hooks, wrap_app=middleware.ParsableErrorMiddleware, guess_content_type_from_ext=False ) if pecan_config.app.enable_acl: return acl.install(app, cfg.CONF) return app
def test_single_blacklist_item(self): _stdout = StringIO() class RootController(object): @expose() def index(self): return 'Hello, World!' app = TestApp( make_app( RootController(), hooks=lambda: [ RequestViewerHook( config={'blacklist': ['/']}, writer=_stdout ) ] ) ) response = app.get('/') out = _stdout.getvalue() assert response.status_int == 200 assert response.body == b_('Hello, World!') assert out == ''
def _serve(self): # Load stored authentication keys self.keys = self.get_config_json("keys") or {} jsonify._instance = jsonify.GenericJSON( sort_keys=True, indent=4, separators=(',', ': '), ) cert = self.get_config_json("cert") or '/etc/ceph/ceph-mgr-restful.crt' pkey = self.get_config_json("pkey") or '/etc/ceph/ceph-mgr-restful.key' # Create the HTTPS werkzeug server serving pecan app self.server = make_server( host='0.0.0.0', port=8003, app=make_app( root='restful.api.Root', hooks = lambda: [ErrorHook()], ), ssl_context=(cert, pkey), ) self.server.serve_forever()
def setup_app(pecan_config=None, extra_hooks=None): if not pecan_config: pecan_config = get_pecan_config() pecan.configuration.set_config(dict(pecan_config), overwrite=True) app_hooks = [hooks.ConfigHook(), hooks.AgentAPIHook(), hooks.ConductorAPIHook(), hooks.ContextHook(pecan_config.app.acl_public_routes), hooks.PublicUrlHook()] if extra_hooks: app_hooks.extend(extra_hooks) app = pecan.make_app( pecan_config.app.root, static_root=pecan_config.app.static_root, debug=False, force_canonical=getattr(pecan_config.app, 'force_canonical', True), hooks=app_hooks, wrap_app=middleware.ParsableErrorMiddleware ) app = middleware.AuthTokenMiddleware( app, dict(cfg.CONF), public_api_routes=pecan_config.app.acl_public_routes) return app
def setup_app(*args, **kwargs): config = { 'server': { 'port': cfg.CONF.bind_port, 'host': cfg.CONF.bind_host }, 'app': { 'root': 'tricircle.nova_apigw.controllers.root.RootController', 'modules': ['tricircle.nova_apigw'], 'errors': { 400: '/error', '__force_dict__': True } } } pecan_config = pecan.configuration.conf_from_dict(config) app_hooks = [root.ErrorHook()] app = pecan.make_app( pecan_config.app.root, debug=False, wrap_app=restapp.auth_app, force_canonical=False, hooks=app_hooks, guess_content_type_from_ext=True ) return app
def setup_app(pecan_config): model.init_model() if not pecan_config: pecan_config = get_pecan_config() config = dict(pecan_config) config["database"] = CONF["admin_api"]["db_sections"] config["gearman"] = { "server": CONF["gearman"]["servers"], "ssl_key": CONF["gearman"]["ssl_key"], "ssl_cert": CONF["gearman"]["ssl_cert"], "ssl_ca": CONF["gearman"]["ssl_ca"], "keepalive": CONF["gearman"]["keepalive"], "keepcnt": CONF["gearman"]["keepcnt"], "keepidle": CONF["gearman"]["keepidle"], "keepintvl": CONF["gearman"]["keepintvl"], } if CONF["debug"]: config["wsme"] = {"debug": True} config["app"]["debug"] = True pecan.configuration.set_config(config, overwrite=True) app = pecan.make_app( pecan_config.app.root, static_root=pecan_config.app.static_root, template_path=pecan_config.app.template_path, debug=getattr(pecan_config.app, "debug", False), force_canonical=getattr(pecan_config.app, "force_canonical", True), guess_content_type_from_ext=getattr(pecan_config.app, "guess_content_type_from_ext", True), ) return app
def setup_app(pecan_config=None, extra_hooks=None): policy.init() app_hooks = [hooks.ConfigHook(), hooks.DBHook(), hooks.ContextHook(pecan_config.app.acl_public_routes), hooks.RPCHook(), hooks.NoExceptionTracebackHook()] if extra_hooks: app_hooks.extend(extra_hooks) if not pecan_config: pecan_config = get_pecan_config() pecan.configuration.set_config(dict(pecan_config), overwrite=True) app = pecan.make_app( pecan_config.app.root, static_root=pecan_config.app.static_root, debug=CONF.debug, force_canonical=getattr(pecan_config.app, 'force_canonical', True), hooks=app_hooks, wrap_app=middleware.ParsableErrorMiddleware, ) if pecan_config.app.enable_acl: return acl.install(app, cfg.CONF, pecan_config.app.acl_public_routes) return app
def setup_app(pecan_config=None, extra_hooks=None): # FIXME: Replace DBHook with a hooks.TransactionHook app_hooks = [hooks.ConfigHook(), hooks.DBHook()] if extra_hooks: app_hooks.extend(extra_hooks) if not pecan_config: pecan_config = get_pecan_config() if pecan_config.app.enable_acl: app_hooks.append(acl.AdminAuthHook()) configuration.set_config(dict(pecan_config), overwrite=True) app = make_app( pecan_config.app.root, static_root=pecan_config.app.static_root, template_path=pecan_config.app.template_path, logging=getattr(pecan_config, 'logging', {}), debug=getattr(pecan_config.app, 'debug', False), force_canonical=getattr(pecan_config.app, 'force_canonical', True), hooks=app_hooks, wrap_app=middleware.ParsableErrorMiddleware, ) if pecan_config.app.enable_acl: return acl.install(app, cfg.CONF) return app
def setup_app(config=None): if not config: config = get_pecan_config() app_conf = dict(config.app) app = pecan.make_app( app_conf.pop('root'), logging=getattr(config, 'logging', {}), wrap_app=middleware.ParsableErrorMiddleware, **app_conf ) app = auth.install(app, CONF, config.app.acl_public_routes) # CORS must be the last one. app = cors.CORS(app, CONF) app.set_latent( allow_headers=['X-Auth-Token', 'X-Identity-Status', 'X-Roles', 'X-Service-Catalog', 'X-User-Id', 'X-Tenant-Id', 'X-OpenStack-Request-ID', 'X-Server-Management-Url'], allow_methods=['GET', 'PUT', 'POST', 'DELETE', 'PATCH'], expose_headers=['X-Auth-Token', 'X-Subject-Token', 'X-Service-Token', 'X-OpenStack-Request-ID', 'X-Server-Management-Url'] ) return app
def setup_app(pecan_config=None, extra_hooks=None): # FIXME: Replace DBHook with a hooks.TransactionHook app_hooks = [hooks.ConfigHook(), hooks.DBHook( storage.get_connection_from_config(cfg.CONF, 'metering'), storage.get_connection_from_config(cfg.CONF, 'event'), storage.get_connection_from_config(cfg.CONF, 'alarm'),), hooks.PipelineHook(), hooks.TranslationHook()] if extra_hooks: app_hooks.extend(extra_hooks) if not pecan_config: pecan_config = get_pecan_config() pecan.configuration.set_config(dict(pecan_config), overwrite=True) cfg.set_defaults(API_OPTS, pecan_debug=CONF.debug) app = pecan.make_app( pecan_config.app.root, debug=CONF.api.pecan_debug, force_canonical=getattr(pecan_config.app, 'force_canonical', True), hooks=app_hooks, wrap_app=middleware.ParsableErrorMiddleware, guess_content_type_from_ext=False ) return app
def test_bad_response_from_app(self): """When exceptions are raised the hook deals with them properly""" _stdout = StringIO() class RootController(object): @expose() def index(self): return 'Hello, World!' app = TestApp( make_app( RootController(), hooks=lambda: [ RequestViewerHook(writer=_stdout) ] ) ) response = app.get('/404', expect_errors=True) out = _stdout.getvalue() assert response.status_int == 404 assert 'path' in out assert 'method' in out assert 'status' in out assert 'method' in out assert 'params' in out assert 'hooks' in out assert '404 Not Found' in out assert "['RequestViewerHook']" in out assert '/' in out
def test_logging_setup_with_config_obj(self): class RootController(object): @expose() def index(self): import logging logging.getLogger('pecantesting').info('HELLO WORLD') return "HELLO WORLD" f = StringIO() from pecan.configuration import conf_from_dict app = TestApp(make_app(RootController(), logging=conf_from_dict({ 'loggers': { 'pecantesting': { 'level': 'INFO', 'handlers': ['memory'] } }, 'handlers': { 'memory': { 'level': 'INFO', 'class': 'logging.StreamHandler', 'stream': f } } }))) app.get('/') assert f.getvalue() == 'HELLO WORLD\n'
def setup_app(pecan_config=None, conf=None): if conf is None: raise RuntimeError("No configuration passed") # FIXME: Replace DBHook with a hooks.TransactionHook app_hooks = [hooks.ConfigHook(conf), hooks.DBHook(conf), hooks.NotifierHook(conf), hooks.TranslationHook()] pecan_config = pecan_config or { "app": { 'root': 'ceilometer.api.controllers.root.RootController', 'modules': ['ceilometer.api'], } } pecan.configuration.set_config(dict(pecan_config), overwrite=True) app = pecan.make_app( pecan_config['app']['root'], hooks=app_hooks, wrap_app=middleware.ParsableErrorMiddleware, guess_content_type_from_ext=False ) return app
def test_callable_error_handler(self): class ColorSchema(Schema): colors = ForEach(validators.String(not_empty=True)) class RootController(object): @expose() def errors(self, *args, **kwargs): return 'There was an error!' @expose(schema=ColorSchema(), error_handler=lambda: '/errors', variable_decode=True) def index(self, **kwargs): return 'Success!' # test with error handler app = TestApp(make_app(RootController())) r = app.post('/', { 'colors-0' : 'blue', 'colors-1' : 'red' }) assert r.status_int == 200 assert r.body == 'Success!' # test with error handler r = app.post('/', { 'colors-0' : 'blue', 'colors-1' : '' }) assert r.status_int == 200 assert r.body == 'There was an error!'
def setUp(self): super(TestStateAccessWithoutThreadLocals, self).setUp() self.args = None class RootController(object): @expose() def index(self, req, resp): return 'Hello, World!' @expose() def greet(self, req, resp, name): return 'Hello, %s!' % name @expose() def greetmore(self, req, resp, *args): return 'Hello, %s!' % args[0] @expose() def kwargs(self, req, resp, **kw): return 'Hello, %s!' % kw['name'] @expose() def mixed(self, req, resp, first, second, *args): return 'Mixed' class SimpleHook(PecanHook): def before(inself, state): self.args = (state.controller, state.arguments) self.root = RootController() self.app = TestApp(make_app( self.root, hooks=[SimpleHook()], use_context_locals=False ))
def setup_app(pecan_config=None, extra_hooks=None): app_hooks = [hooks.ConfigHook(), hooks.DBHook(), hooks.ContextHook(), hooks.RPCHook(), ] # TODO(sbauza): Add stevedore extensions for loading hooks if extra_hooks: app_hooks.extend(extra_hooks) app = pecan.make_app( pecan_config.app.root, debug=CONF.debug, hooks=app_hooks, wrap_app=middleware.ParsableErrorMiddleware, guess_content_type_from_ext=False ) # WSGI middleware for debugging if CONF.log_exchange: app = debug.Debug.factory(pecan_config)(app) # WSGI middleware for Keystone auth # NOTE(sbauza): ACLs are always active unless for unittesting where # enable_acl could be set to False if pecan_config.app.enable_acl: CONF.register_opts(auth_token.opts, group=OPT_GROUP_NAME) keystone_config = dict(CONF.get(OPT_GROUP_NAME)) app = auth_token.AuthProtocol(app, conf=keystone_config) return app
def test_basic_single_default_hook(self): _stdout = StringIO() class RootController(object): @expose() def index(self): return 'Hello, World!' app = TestApp( make_app( RootController(), hooks=lambda: [ RequestViewerHook(writer=_stdout) ] ) ) response = app.get('/') out = _stdout.getvalue() assert response.status_int == 200 assert response.body == b_('Hello, World!') assert 'path' in out assert 'method' in out assert 'status' in out assert 'method' in out assert 'params' in out assert 'hooks' in out assert '200 OK' in out assert "['RequestViewerHook']" in out assert '/' in out
def setUpClass(cls): """A class method called before tests in an individual class run """ rootController = root_controller.RootController() ControllerTestCase.app = webtest.TestApp( pecan.make_app(rootController)) ControllerTestCase.data = {'info': {'service_type': 'firewall', 'service_vendor': 'vyos', 'context': {}}, 'config': [{'resource': 'firewall', 'resource_data': {}}] }
def setup_app(config=None): if not config: config = get_pecan_config() app_conf = dict(config.app) app = pecan.make_app(app_conf.pop('root'), logging=getattr(config, 'logging', {}), debug=CONF.debug, wrap_app=parsable_error.ParsableErrorMiddleware, **app_conf) return acl.install(app, CONF, config.app.acl_public_routes)
def setup_app(config): models.init_model() app_conf = dict(config.app) app = make_app(app_conf.pop('root'), logging=getattr(config, 'logging', {}), **app_conf) # make a series of health checks, post if they are good async .post_if_healthy() return app
def setup_app(config): """setup method.""" model.init_model() app_conf = dict(config.app) factory.database_url = config.database.url factory.echo_statements = config.database.echo_statements app = make_app(app_conf.pop('root'), logging=getattr(config, 'logging', {}), **app_conf) logger.info('Starting Audit...') return app
def setup_app(config=None): if not config: config = get_pecan_config() app_conf = dict(config.app) common_config.set_config_defaults() app = pecan.make_app(app_conf.pop('root'), logging=getattr(config, 'logging', {}), wrap_app=middleware.ParsableErrorMiddleware, **app_conf) return app
def setup_app(config=None): LOG.info('Creating st2api: %s as Pecan app.', VERSION_STRING) is_gunicorn = getattr(config, 'is_gunicorn', False) if is_gunicorn: st2api_config.register_opts() # This should be called in gunicorn case because we only want # workers to connect to db, rabbbitmq etc. In standalone HTTP # server case, this setup would have already occurred. common_setup(service='api', config=st2api_config, setup_db=True, register_mq_exchanges=True, register_signal_handlers=True, register_internal_trigger_types=True, run_migrations=True, config_args=config.config_args) if not config: # standalone HTTP server case config = _get_pecan_config() else: # gunicorn case if is_gunicorn: config.app = _get_pecan_config().app app_conf = dict(config.app) active_hooks = [ hooks.RequestIDHook(), hooks.JSONErrorResponseHook(), hooks.LoggingHook() ] if cfg.CONF.auth.enable: active_hooks.append(hooks.AuthHook()) active_hooks.append(hooks.CorsHook()) app = pecan.make_app(app_conf.pop('root'), logging=getattr(config, 'logging', {}), hooks=active_hooks, **app_conf) # Static middleware which servers common static assets such as logos static_root = os.path.join(BASE_DIR, 'public') app = StaticFileMiddleware(app=app, directory=static_root) LOG.info('%s app created.' % __name__) return app
def test_nested_get_all(self): class BarsController(RestController): @expose() def get_one(self, foo_id, id): return '4' @expose() def get_all(self, foo_id): return '3' class FoosController(RestController): bars = BarsController() @expose() def get_one(self, id): return '2' @expose() def get_all(self): return '1' class RootController(object): foos = FoosController() # create the app app = TestApp(make_app(RootController())) r = app.get('/foos/') assert r.status_int == 200 assert r.body == b_('1') r = app.get('/foos/1/') assert r.status_int == 200 assert r.body == b_('2') r = app.get('/foos/1/bars/') assert r.status_int == 200 assert r.body == b_('3') r = app.get('/foos/1/bars/2/') assert r.status_int == 200 assert r.body == b_('4') r = app.get('/foos/bars/', status=404) assert r.status_int == 404 r = app.get('/foos/bars/1', status=404) assert r.status_int == 404
def setup_app(config): """App factory.""" # By default we expect path to oslo config file in environment variable # REFSTACK_OSLO_CONFIG (option for testing and development) # If it is empty we look up those config files # in the following directories: # ~/.${project}/ # ~/ # /etc/${project}/ # /etc/ default_config_files = ((os.getenv('REFSTACK_OSLO_CONFIG'), ) if os.getenv('REFSTACK_OSLO_CONFIG') else cfg.find_config_files('refstack')) CONF('', project='refstack', default_config_files=default_config_files) log.setup(CONF, 'refstack') CONF.log_opt_values(LOG, logging.DEBUG) template_path = CONF.api.template_path % {'project_root': PROJECT_ROOT} static_root = CONF.api.static_root % {'project_root': PROJECT_ROOT} app_conf = dict(config.app) app = pecan.make_app( app_conf.pop('root'), debug=CONF.api.app_dev_mode, static_root=static_root, template_path=template_path, hooks=[JSONErrorHook(), CORSHook(), pecan.hooks.RequestViewerHook( {'items': ['status', 'method', 'controller', 'path', 'body']}, headers=False, writer=WritableLogger(LOG, logging.DEBUG) )] ) beaker_conf = { 'session.key': 'refstack', 'session.type': 'ext:database', 'session.url': CONF.database.connection, 'session.timeout': 604800, 'session.validate_key': api_utils.get_token(), 'session.sa.pool_recycle': 600 } app = SessionMiddleware(app, beaker_conf) if CONF.api.app_dev_mode: LOG.debug('\n\n <<< Refstack UI is available at %s >>>\n\n', CONF.ui_url) return app
def setup_app(config): # model.init_model() # mock db # here we init the connection to RabbitMQ message_server = '192.168.1.220' connection.get_client(message_server) app_conf = dict(config.app) return make_app(app_conf.pop('root'), logging=getattr(config, 'logging', {}), **app_conf)
def setup_app(config): return make_app( config.app.root, static_root=config.app.static_root, template_path=config.app.template_path, logging=getattr(config, 'logging', {}), debug=getattr(config.app, 'debug', False), force_canonical=getattr(config.app, 'force_canonical', True), guess_content_type_from_ext=getattr( config.app, 'guess_content_type_from_ext', True), )
def setup_app(config=None): LOG.info('Creating st2stream: %s as Pecan app.', VERSION_STRING) is_gunicorn = getattr(config, 'is_gunicorn', False) if is_gunicorn: # Note: We need to perform monkey patching in the worker. If we do it in # the master process (gunicorn_config.py), it breaks tons of things # including shutdown monkey_patch() st2stream_config.register_opts() # This should be called in gunicorn case because we only want # workers to connect to db, rabbbitmq etc. In standalone HTTP # server case, this setup would have already occurred. common_setup(service='stream', config=st2stream_config, setup_db=True, register_mq_exchanges=True, register_signal_handlers=True, register_internal_trigger_types=False, run_migrations=False, config_args=config.config_args) if not config: # standalone HTTP server case config = _get_pecan_config() else: # gunicorn case if is_gunicorn: config.app = _get_pecan_config().app app_conf = dict(config.app) active_hooks = [ hooks.RequestIDHook(), hooks.JSONErrorResponseHook(), hooks.LoggingHook() ] active_hooks.append(hooks.AuthHook()) active_hooks.append(hooks.CorsHook()) app = pecan.make_app(app_conf.pop('root'), logging=getattr(config, 'logging', {}), hooks=active_hooks, **app_conf) LOG.info('%s app created.' % __name__) return app
def create_app(): pecan_conf = get_pecan_config() app_hooks = [hooks.ConfigHook(), hooks.DatabaseHook()] pecan.configuration.set_config(dict(pecan_conf), overwrite=True) app = pecan.make_app(pecan_conf.app.root, static_root=pecan_conf.app.static_root, debug=False, force_canonical=getattr(pecan_conf.app, 'force_canonical', True), hooks=app_hooks) return app
def setup_app(root, conf=None): app_hooks = [hooks.ConfigHook(conf), hooks.TranslationHook(), hooks.RPCHook(conf), hooks.ContextHook(), hooks.DBHook(conf)] app = pecan.make_app( root, hooks=app_hooks, guess_content_type_from_ext=False ) return app
def setup_app(pecan_config): config = dict(pecan_config) config['app']['debug'] = cfg.CONF['service:api'].pecan_debug pecan.configuration.set_config(config, overwrite=True) app = pecan.make_app(pecan_config.app.root, debug=getattr(pecan_config.app, 'debug', False), force_canonical=getattr(pecan_config.app, 'force_canonical', True), request_cls=patches.Request) return app
def setup_app(config=None): service.prepare_service("gapi", sys.argv) if not config: config = get_pecan_config() app_conf = dict(config.app) app = pecan.make_app( app_conf.pop('root'), force_canonical=False, logging=getattr(config, 'logging', {}), **app_conf ) return app
def test_nested_rest_with_default(self): class FooController(RestController): @expose() def _default(self, *remainder): return "DEFAULT %s" % remainder class RootController(RestController): foo = FooController() app = TestApp(make_app(RootController())) r = app.get('/foo/missing') assert r.status_int == 200 assert r.body == b_("DEFAULT missing")
def test_proper_allow_header_multiple_gets(self): class ThingsController(RestController): @expose() def get_all(self): return dict() @expose() def get(self): return dict() app = TestApp(make_app(ThingsController())) r = app.put('/123', status=405) assert r.status_int == 405 assert r.headers['Allow'] == 'GET'
def setup_app(pecan_config=None, debug=False, argv=None): """Creates and returns a pecan wsgi app.""" warder_service.prepare_service(argv) cfg.CONF.log_opt_values(LOG, logging.DEBUG) if not pecan_config: pecan_config = get_pecan_config() pecan.configuration.set_config(dict(pecan_config), overwrite=True) return pecan.make_app(pecan_config.app.root, wrap_app=_wrap_app, debug=debug, hooks=pecan_config.app.hooks, wsme=pecan_config.wsme)
def test_method_not_allowed_get(self): class ThingsController(RestController): @expose() def put(self, id_, value): response.status = 200 @expose() def delete(self, id_): response.status = 200 app = TestApp(make_app(ThingsController())) r = app.get('/', status=405) assert r.status_int == 405 assert r.headers['Allow'] == 'DELETE, PUT'
def setup_app(config): model.init_model() token_conf = authentication._get_token_conf(config) policy.init(config.authentication.policy_file, token_conf) app_conf = dict(config.app) # setting configurations for utils to be used from now and on utils.set_utils_conf(config) app = make_app(app_conf.pop('root'), logging=getattr(config, 'logging', {}), **app_conf) logger.info('Starting CMS...') return app
def setup_app(config=None): if not config: config = get_pecan_config() app_conf = dict(config.app) app = pecan.make_app( app_conf.pop('root'), force_canonical=False, logging=getattr(config, 'logging', {}), context_local_factory=local, **app_conf ) return app
def setup_app(config): # initial logging, will be re-configured later logging.basicConfig(stream=sys.stdout, level=logging.DEBUG) app_conf = dict(config.app) load_config() validate_config(jsonloader.conf) audit.init_audit() app = pecan.make_app(app_conf.pop('root'), logging=config.logging, **app_conf) return paste.translogger.TransLogger(app, setup_console_handler=False)
def app_factory(global_config, **local_config): print "######### enter app_factory" conf = service.prepareService() # NOTE, add config and databse information to the request # by using pecan.hooks.PecanHook configHook = hooks.ConfigHook(conf) conn = db.getConnectionFromConfig(conf) databaseHook = hooks.DatabaseHook(conn) appHooks = [configHook, databaseHook] # NOTE, it needs add the line below pecan.configuration.set_config(dict(PECAN_CONFIG), overwrite=True) app = pecan.make_app(PECAN_CONFIG['app']['root'], hooks=appHooks) return app
def setup_app(config=None): app_conf = { 'root': "multivimbroker.api_v2.api_router.root.RootController", 'modules': ["multivimbroker.api_v2"], 'debug': True, # NOTE: By default, guess_content_type_from_ext is True, and Pecan will # strip the file extension from url. For example, ../../swagger.json # will look like ../../swagger to Pecan API router. This makes other # url like ../../swagger.txt get the same API route. Set this to False # to do strict url mapping. 'guess_content_type_from_ext': False } app = pecan.make_app(app_conf.pop('root'), **app_conf) return app
def setup_app(config): model.init_model() app_conf = dict(config.app) return make_app( app_conf.pop('root'), logging=getattr(config, 'logging', {}), hooks=[TransactionHook(model.start, model.start, model.commit, model.rollback, model.clear)], **app_conf )
def test_prioritized_hooks(self): run_hook = [] class RootController(object): @expose() def index(self): run_hook.append('inside') return 'Hello, World!' class SimpleHook(PecanHook): def __init__(self, id, priority=None): self.id = str(id) if priority: self.priority = priority def on_route(self, state): run_hook.append('on_route' + self.id) def before(self, state): run_hook.append('before' + self.id) def after(self, state): run_hook.append('after' + self.id) def on_error(self, state, e): run_hook.append('error' + self.id) papp = make_app( RootController(), hooks=[SimpleHook(1, 3), SimpleHook(2, 2), SimpleHook(3, 1)]) app = TestApp(papp) response = app.get('/') assert response.status_int == 200 assert response.body == b_('Hello, World!') assert len(run_hook) == 10 assert run_hook[0] == 'on_route3' assert run_hook[1] == 'on_route2' assert run_hook[2] == 'on_route1' assert run_hook[3] == 'before3' assert run_hook[4] == 'before2' assert run_hook[5] == 'before1' assert run_hook[6] == 'inside' assert run_hook[7] == 'after1' assert run_hook[8] == 'after2' assert run_hook[9] == 'after3'
def setup_app(config=None, extra_hooks=None): if not config: config = get_pecan_config() app_conf = dict(config.app) rpcclient = rpcapi.AgentAPI() app_hooks = [hooks.DBHook(), hooks.RPCHook(rpcclient)] app = pecan.make_app(app_conf.pop('root'), hooks=app_hooks, logging=getattr(config, 'logging', {}), **app_conf) return app
def setup_app(config=None, extra_hooks=None): app_hooks = [hooks.ConfigHook()] if extra_hooks: app_hooks.extend(extra_hooks) if not config: config = get_pecan_config() pecan.configuration.set_config(dict(config), overwrite=True) app = pecan.make_app('keystone.contrib.kds.api.root.RootController', debug=CONF.debug, hooks=app_hooks) return app
def setup_app(pecan_config=None, debug=False, argv=None): """Creates and returns a pecan wsgi app.""" octavia_service.prepare_service(argv) app_hooks = [hooks.ContextHook()] if not pecan_config: pecan_config = get_pecan_config() pecan.configuration.set_config(dict(pecan_config), overwrite=True) return pecan.make_app( pecan_config.app.root, debug=debug, hooks=app_hooks, wsme=pecan_config.wsme )
def setup_app(pecan_config=None): if not pecan_config: pecan_config = get_pecan_config() pecan.configuration.set_config(dict(pecan_config), overwrite=True) app = pecan.make_app( pecan_config.app.root, static_root=pecan_config.app.static_root, template_path=pecan_config.app.template_path, debug=False, force_canonical=getattr(pecan_config.app, 'force_canonical', True), guess_content_type_from_ext=False, # Avoid mime-type lookup ) return app