Python bottle.Bottle() Examples
The following are 30
code examples of bottle.Bottle().
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
bottle
, or try the search function
.
Example #1
Source File: test_bottle.py From sentry-python with BSD 2-Clause "Simplified" License | 6 votes |
def test_logging(sentry_init, capture_events, app, get_client): # ensure that Bottle's logger magic doesn't break ours sentry_init( integrations=[ bottle_sentry.BottleIntegration(), LoggingIntegration(event_level="ERROR"), ] ) @app.route("/") def index(): app.logger.error("hi") return "ok" events = capture_events() client = get_client() client.get("/") (event,) = events assert event["level"] == "error"
Example #2
Source File: app.py From glim with MIT License | 6 votes |
def __init__(self, commandadapter, mconfig=None, mroutes=None, mcontrollers=None, env='default', before=None): # register app self.commandadapter = commandadapter self.config = mconfig.config self.urls = mroutes.urls self.mcontrollers = mcontrollers; self.wsgi = Bottle() self.register_config() self.register_log() self.register_extensions() self.register_ssl_context() self.register_routes() self.before = before self.before()
Example #3
Source File: webserver.py From awe with MIT License | 6 votes |
def __init__(self, exporter, host, port, websocket_port, custom_component, encoder, api): self._api = api self._host = host self._port = port self._websocket_port = websocket_port self._exporter = exporter self._custom_component = custom_component self._encoder = encoder self._get_initial_state = exporter.get_initial_state self._client_root = exporter.client_root self._content_root = os.path.join(os.path.dirname(__file__), 'resources', self._client_root) self._app = bottle.Bottle() self._app.get('/', callback=self._index) self._app.get('/initial-state', callback=self._initial_state) self._app.get('/export', callback=self._export) self._app.get('/static/<path:path>', callback=self._get_static_file) self._app.get('/custom-components', callback=self._components) self._api.register(self._app) self._thread = threading.Thread(target=self._run) self._thread.daemon = True
Example #4
Source File: server.py From nematus with BSD 3-Clause "New" or "Revised" License | 6 votes |
def __init__(self, server_settings): """ Loads a translation model and initialises the webserver. @param server_settings: see `settings.py` """ self._style = server_settings.style self._host = server_settings.host self._port = server_settings.port self._threads = server_settings.threads self._debug = server_settings.verbose self._models = server_settings.models self._num_processes = server_settings.num_processes self._status = self.STATUS_LOADING # start webserver self._server = Bottle() self._server.config['logging.level'] = 'DEBUG' if server_settings.verbose else 'WARNING' self._server.config['logging.format'] = '%(levelname)s: %(message)s' self._server.install(LoggingPlugin(self._server.config)) logging.info("Starting Nematus Server") # start translation workers logging.info("Loading translation models") self._translator = Translator(server_settings) self._status = self.STATUS_OK
Example #5
Source File: test_bottle.py From aws-xray-sdk-python with Apache License 2.0 | 6 votes |
def test_lambda_default_ctx(): # Track to make sure that Bottle will default to generating segments if context is not the lambda context new_recorder = get_new_stubbed_recorder() new_recorder.configure(service='test', sampling=False) new_app = Bottle() @new_app.route('/segment') def segment_(): # Test in between request and make sure Lambda that uses default context generates a segment. assert new_recorder.current_segment() assert type(new_recorder.current_segment()) == segment_model.Segment return 'ok' new_app.install(XRayMiddleware(new_recorder)) app_client = WebApp(new_app) path = '/segment' app_client.get(path) segment = recorder.emitter.pop() assert not segment # Segment should be none because it's created and ended by the plugin
Example #6
Source File: conftest.py From bottle-jwt with GNU General Public License v3.0 | 6 votes |
def bottle_app(backend): """pytest fixture for `bottle.Bottle` instance. """ app = bottle.Bottle() jwt_plugin = JWTProviderPlugin( keyword='jwt', auth_endpoint='/auth', backend=backend, fields=('username', 'password'), secret='my_secret', ttl=3 ) app.install(jwt_plugin) @app.get('/') @jwt_auth_required def private_resource(): return {'user': bottle.request.get_user()} return webtest.TestApp(app)
Example #7
Source File: gnomecast.py From gnomecast with GNU General Public License v3.0 | 6 votes |
def __init__(self): self.ip = (([ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith("127.")] or [[(s.connect(("8.8.8.8", 53)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1]]) + [None])[0] with contextlib.closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s: s.bind(('0.0.0.0', 0)) self.port = s.getsockname()[1] self.app = bottle.Bottle() self.cast = None self.last_known_player_state = None self.last_known_current_time = None self.last_time_current_time = None self.fn = None self.video_stream = None self.audio_stream = None self.last_fn_played = None self.transcoder = None self.duration = None self.subtitles = None self.seeking = False self.last_known_volume_level = None bus = dbus.SessionBus() if DBUS_AVAILABLE else None self.saver_interface = find_screensaver_dbus_iface(bus) self.inhibit_screensaver_cookie = None self.autoplay = False
Example #8
Source File: bsc.py From AIT-Core with MIT License | 6 votes |
def __init__(self, logger_manager, host, port): ''' Args: logger_manager: Instance of :class:`StreamCaptureManager` which the server will use to manage logger instances. host: The host for webserver configuration. port: The port for webserver configuration. ''' self._host = host self._port = port self._logger_manager = logger_manager self._app = Bottle() self._route()
Example #9
Source File: sm_ansible_server.py From contrail-server-manager with Apache License 2.0 | 6 votes |
def __init__(self, args_str=None): try: self._smgr_log = ServerMgrlogger() except: print "Error Creating logger object" self._smgr_log.log(self._smgr_log.INFO, "Starting SM Ansible Server") if not args_str: args_str = sys.argv[1:] self._parse_args(args_str) self.joinq = Queue.Queue() self.joiner = Joiner(self.joinq) self.joiner.start() self._smgr_log.log(self._smgr_log.INFO, 'Initializing Bottle App') self.app = bottle.app() bottle.route('/run_ansible_playbooks', 'POST', self.start_ansible_playbooks)
Example #10
Source File: test_bottle.py From aws-xray-sdk-python with Apache License 2.0 | 5 votes |
def view_(name='bottle'): return dict(name=name) # add X-Ray plugin to Bottle app
Example #11
Source File: node.py From crankycoin with MIT License | 5 votes |
def __init__(self, peers, api_client, blockchain, mempool, validator): super(FullNode, self).__init__(peers, api_client) mp.log_to_stderr() mp_logger = mp.get_logger() mp_logger.setLevel(logging.DEBUG) self.app = Bottle() self.app.merge(public_app) self.app.merge(permissioned_app) self.blockchain = blockchain self.mempool = mempool self.validator = validator
Example #12
Source File: test_bottle.py From aws-xray-sdk-python with Apache License 2.0 | 5 votes |
def test_render_view(): path = '/view' response = app.get(path) assert response.text == "<h1>Hello Bottle!</h1>\n<p>How are you?</p>\n" segment = recorder.emitter.pop() assert not segment.in_progress # segment should contain a template render subsegment assert segment.subsegments subsegment = segment.subsegments[0] assert subsegment.name assert subsegment.namespace == 'local' assert not subsegment.in_progress
Example #13
Source File: webRequestHandler.py From LED-bot with MIT License | 5 votes |
def __init__(self,host='0.0.0.0',port=4000): self.here = dirname(__file__) self.www = Bottle() self.callback = None self.routes() server = Thread(target=self.www.run,kwargs=dict(host=host, port=port)); server.setDaemon(True) server.start()
Example #14
Source File: rest_api_server.py From bii-server with MIT License | 5 votes |
def __init__(self, server_store): self.__server_store = server_store self.root_app = bottle.Bottle() api_v1.app.store = server_store self.root_app.mount("/v1/", api_v1.app) #self.__root_app.mount("/v2/",api_v2.app)
Example #15
Source File: rest_api_server.py From bii-server with MIT License | 5 votes |
def run(self, **kwargs): port = kwargs.pop("port", BIISERVER_RUN_PORT) debug_set = kwargs.pop("debug", False) bottle.Bottle.run(self.root_app, host="localhost", port=port, debug=debug_set, reloader=False)
Example #16
Source File: memvisu.py From scat with MIT License | 5 votes |
def __init__(self, config, json_path): super(MemVisu, self).__init__() self.__port = config["port"] self.__path = config["path"] self.__app = bottle.Bottle() with open(json_path, "r") as f: self.__data = json.loads(f.read()) self.__route()
Example #17
Source File: server_mgr_status.py From contrail-server-manager with Apache License 2.0 | 5 votes |
def run(self): #create the logger try: self._smgr_log = ServerMgrlogger() except: print "Error Creating logger object" # Connect to the cluster-servers database try: self._status_serverDb = db( self._smgr_main._args.server_manager_base_dir+self._smgr_main._args.database_name) except: self._smgr_log.log(self._smgr_log.DEBUG, "Error Connecting to Server Database %s" % (self._smgr_main._args.server_manager_base_dir+self._smgr_main._args.database_name)) exit() #set the status related handlers status_bottle_app = Bottle() status_bottle_app.route('/server_status', 'POST', self.put_server_status) status_bottle_app.route('/server_status', 'PUT', self.put_server_status) status_bottle_app.route('/ansible_status', 'PUT', self.put_ansible_status) try: bottle.run(status_bottle_app, host=self._status_thread_config['listen_ip'], port=self._status_thread_config['listen_port']) except Exception as e: # cleanup gracefully exit()
Example #18
Source File: webhook.py From squadron with MIT License | 5 votes |
def __init__(self, username, password, callback, log): self.username = username self.password = password self.callback = callback self.log = log self.application = bottle.Bottle() self.application.route('/', method='POST', callback=self.handle)
Example #19
Source File: test_notify.py From squadron with MIT License | 5 votes |
def test_server(): thread, serv = server.get_server('127.0.0.1', 34890, bottle.Bottle()) thread.start() time.sleep(1) serv.stop() thread.join(2) assert not thread.isAlive()
Example #20
Source File: integration_tests.py From cccatalog-api with MIT License | 5 votes |
def _wait_for_callback(self, endpoint_name="/task_done"): """ Block until a callback arrives. Time out if it doesn't arrive within 10 seconds. :param endpoint_name: :return: """ callback_listener = Bottle() # Signal when a callback has been received callback_received = multiprocessing.Value('i', 0) @callback_listener.route(endpoint_name, method="post") def handle_task_callback(): callback_received.value = 1 return HTTPResponse(status=204) kwargs = { 'host': _get_host_ip(), 'port': 58000, 'quiet': (not ENABLE_DETAILED_LOGS) } cb_listener_process = Process( target=run, args=(callback_listener,), kwargs=kwargs ) cb_listener_process.start() timeout_seconds = 10 poll_time = 0.1 running_time = 0 while callback_received.value != 1: running_time += poll_time time.sleep(poll_time) if running_time >= timeout_seconds: cb_listener_process.terminate() self.fail('Timed out waiting for task callback.') cb_listener_process.terminate()
Example #21
Source File: webrecrecorder.py From conifer with Apache License 2.0 | 5 votes |
def init_app(self, storage_committer=None): self.storage_committer = storage_committer self.init_recorder() self.app = Bottle() self.app.mount('/record', self.recorder) debug(True)
Example #22
Source File: __init__.py From NSC_BUILDER with MIT License | 5 votes |
def spawn(function, *args, **kwargs): return gvt.spawn(function, *args, **kwargs) # Bottle Routes
Example #23
Source File: box.py From box-python-sdk with Apache License 2.0 | 5 votes |
def __init__(self): debug(True) self._db_engine = None self._db_session = None self._db_session_maker = None self.reset_filesystem() # Mock Box consists of 3 webservers - one for the content API, one for the upload API, and one for OAuth2 api, upload, oauth_api, event, oauth_authorize = Bottle(), Bottle(), Bottle(), Bottle(), Bottle() app_mapping = { self.API_PORT: api, self.EVENT_PORT: event, self.OAUTH_API_PORT: oauth_api, self.UPLOAD_PORT: upload, self.OAUTH_AUTHORIZE_PORT: oauth_authorize, } # Since we don't instantiate the servers until Box is instantiated, we have to apply the routes now for routed_method in (getattr(self, m) for m in dir(self) if hasattr(getattr(self, m), 'route')): app_port = routed_method.app app = app_mapping[app_port] app.route(routed_method.route, routed_method.verb, routed_method) for code in [400, 401, 404, 409, 429, 500]: for app in app_mapping.values(): app.error(code)(self.handle_error) self._api = StoppableWSGIRefServer(host='localhost', port=self.API_PORT).run(api) self._upload = StoppableWSGIRefServer(host='localhost', port=self.UPLOAD_PORT).run(upload) self._oauth_api = StoppableWSGIRefServer(host='localhost', port=self.OAUTH_API_PORT).run(oauth_api) self._event = StoppableWSGIRefServer(host='localhost', port=self.EVENT_PORT).run(event) self._oauth_authorize = StoppableWSGIRefServer(host='localhost', port=self.OAUTH_AUTHORIZE_PORT).run(oauth_authorize) self._rate_limit_bucket = (self.RATE_LIMIT_THRESHOLD, datetime.utcnow())
Example #24
Source File: test_bottle.py From sentry-python with BSD 2-Clause "Simplified" License | 5 votes |
def app(sentry_init): app = Bottle() @app.route("/message") def hi(): capture_message("hi") return "ok" @app.route("/message-named-route", name="hi") def named_hi(): capture_message("hi") return "ok" yield app
Example #25
Source File: cprofilev.py From cprofilev with MIT License | 5 votes |
def __init__(self, profile, title, address='127.0.0.1', port=4000): self.profile = profile self.title = title self.port = port self.address = address # Bottle webserver. self.app = bottle.Bottle() self.app.route('/')(self.route_handler)
Example #26
Source File: __init__.py From Eel with MIT License | 5 votes |
def spawn(function, *args, **kwargs): return gvt.spawn(function, *args, **kwargs) # Bottle Routes
Example #27
Source File: test.py From bottle-react with MIT License | 5 votes |
def test_hello_world(self): app = bottle.Bottle() br = bottlereact.BottleReact(app, prod=True) html = br.render_html(br.HelloWorld()) self.assertTrue(html.startswith('<html>')) self.assertTrue('-bottlereact.js"></script>' in html) self.assertTrue('-hello_world.js"></script>' in html) self.assertTrue('React.createElement(bottlereact.HelloWorld,{},[])' in html)
Example #28
Source File: test.py From bottle-react with MIT License | 5 votes |
def test_kwarg(self): app = bottle.Bottle() br = bottlereact.BottleReact(app, prod=True) html = br.render_html(br.HelloWorld(), template='title', title='xyz').strip() self.assertEqual(html, 'xyz')
Example #29
Source File: test.py From bottle-react with MIT License | 5 votes |
def test_default_kwarg(self): app = bottle.Bottle() br = bottlereact.BottleReact(app, prod=True, default_render_html_kwargs={'title':'abc'}) html = br.render_html(br.HelloWorld(), template='title').strip() self.assertEqual(html, 'abc') html = br.render_html(br.HelloWorld(), template='title', title='xyz').strip() self.assertEqual(html, 'xyz')
Example #30
Source File: test.py From bottle-react with MIT License | 5 votes |
def test_default_kwarg_func(self): def default_render_html_kwargs(): return {'title':'abc'} app = bottle.Bottle() br = bottlereact.BottleReact(app, prod=True, default_render_html_kwargs=default_render_html_kwargs) html = br.render_html(br.HelloWorld(), template='title').strip() self.assertEqual(html, 'abc') html = br.render_html(br.HelloWorld(), template='title', title='xyz').strip() self.assertEqual(html, 'xyz')