Python bottle.run() Examples
The following are 30
code examples of bottle.run().
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: REST.py From im with GNU General Public License v3.0 | 6 votes |
def run(self, handler): try: # First try to use the new version from cheroot.ssl.pyopenssl import pyOpenSSLAdapter from cheroot import wsgi server = wsgi.Server((self.host, self.port), handler, request_queue_size=32) except Exception: from cherrypy.wsgiserver.ssl_pyopenssl import pyOpenSSLAdapter from cherrypy import wsgiserver server = wsgiserver.CherryPyWSGIServer((self.host, self.port), handler, request_queue_size=32) self.srv = server # If cert variable is has a valid path, SSL will be used # You can set it to None to disable SSL server.ssl_adapter = pyOpenSSLAdapter(Config.REST_SSL_CERTFILE, Config.REST_SSL_KEYFILE, Config.REST_SSL_CA_CERTS) try: server.start() finally: server.stop()
Example #2
Source File: server_mgr_mon_base_plugin.py From contrail-server-manager with Apache License 2.0 | 6 votes |
def initialize_features(self, sm_args, serverdb): self.sandesh_init(sm_args, self.monitoring_config_set, self.inventory_config_set) self.set_serverdb(serverdb) if self.monitoring_config_set: self.server_monitoring_obj.set_serverdb(serverdb) self.server_monitoring_obj.set_ipmi_defaults(sm_args.ipmi_username, sm_args.ipmi_password) self.monitoring_gevent_thread_obj = gevent.spawn(self.server_monitoring_obj.run) else: self._smgr_log.log(self._smgr_log.ERROR, "Monitoring configuration not set. " "You will be unable to get Monitor information of servers.") if self.inventory_config_set: self.server_inventory_obj.set_serverdb(serverdb) self.server_inventory_obj.set_ipmi_defaults(sm_args.ipmi_username, sm_args.ipmi_password) self.server_inventory_obj.add_inventory() else: self._smgr_log.log(self._smgr_log.ERROR, "Inventory configuration not set. " "You will be unable to get Inventory information from servers.")
Example #3
Source File: sm_ansible_server.py From contrail-server-manager with Apache License 2.0 | 6 votes |
def main(args_str=None): ''' Spawn the webserver for Ansible operations ''' sm_pid = os.getpid() pid_file = \ "/var/run/contrail-server-manager/contrail-server-manager-ansible.pid" dir = os.path.dirname(pid_file) if not os.path.exists(dir): os.mkdir(dir) f = open(pid_file, "w") f.write(str(sm_pid)) f.close() try: srvr = SMAnsibleServer(args_str) bottle.run(app=srvr.app, host=srvr._args.ansible_srvr_ip, port=srvr._args.ansible_srvr_port, debug=True, server='paste') except Exception as e: print "Container server was not started successfully"
Example #4
Source File: bottle.py From annotated-py-projects with MIT License | 6 votes |
def error(code=500): # 出错处理 -- 写成装饰器函数. """ Decorator for error handler. Same as set_error_handler(code, handler).""" def wrapper(handler): # 包裹函数. set_error_handler(code, handler) return handler return wrapper # 调用 内嵌包裹函数. ############################################################################### ######################## 服务适配器部分 ########################################## # 1. web Server 这部分代码,多是导入现成的包,自己修改处理的代码,很少. # 2. 注意这种开发思想. # 3. 这里有 内嵌函数定义的应用,注意一下. ############################################################################### # Server adapter 服务适配器部分-定义 # 由全局的run()函数, 定位到此处.
Example #5
Source File: youtube-dl-server.py From youtube-dl-nas with MIT License | 6 votes |
def download(url): # url[1].send("[MSG], [Started] downloading " + url[0] + " resolution below " + url[2]) result="" if (url[2] == "best"): result = subprocess.run(["youtube-dl", "-o", "./downfolder/.incomplete/%(title)s.%(ext)s", "-f", "bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]", "--exec", "touch {} && mv {} ./downfolder/", "--merge-output-format", "mp4", url[0]]) elif (url[2] == "audio"): result = subprocess.run(["youtube-dl", "-o", "./downfolder/.incomplete/%(title)s.%(ext)s", "-f", "bestaudio[ext=m4a]", "--exec", "touch {} && mv {} ./downfolder/", url[0]]) else: resolution = url[2][:-1] result = subprocess.run(["youtube-dl", "-o", "./downfolder/.incomplete/%(title)s.%(ext)s", "-f", "bestvideo[height<="+resolution+"]+bestaudio[ext=m4a]", "--exec", "touch {} && mv {} ./downfolder/", url[0]]) try: if(result.returncode==0): url[1].send("[MSG], [Finished] " + url[0] + " resolution below " + url[2]+", Remain download Count "+ json.dumps(dl_q.qsize())) url[1].send("[QUEUE], Remaining download Count : " + json.dumps(dl_q.qsize())) url[1].send("[COMPLETE]," + url[2] + "," + url[0]) else: url[1].send("[MSG], [Finished] downloading failed " + url[0]) url[1].send("[COMPLETE]," + "url access failure" + "," + url[0]) except error: print("Be Thread Safe")
Example #6
Source File: df_rest_service.py From dragonflow with Apache License 2.0 | 6 votes |
def main(): parser = argparse.ArgumentParser(description='Dragonflow REST server') parser.add_argument('--host', type=str, default='127.0.0.1', help='Host to listen on (127.0.0.1)') parser.add_argument('--port', type=int, default=8080, help='Port to listen on (8080)') parser.add_argument('--config', type=str, default='/etc/dragonflow/dragonflow.ini', help=('Dragonflow config file ' '(/etc/dragonflow/dragonflow.ini)')) parser.add_argument('--json', type=str, default=None, help=('JSON schema file (None)')) args = parser.parse_args() global schema_file schema_file = args.json utils.config_init(None, [args.config]) bottle.run(host=args.host, port=args.port)
Example #7
Source File: hindsight_gui.py From hindsight with Apache License 2.0 | 6 votes |
def main(): print(banner) global STATIC_PATH # Get the hindsight module's path on disk to add to sys.path, so we can find templates and static files module_path = os.path.dirname(pyhindsight.__file__) sys.path.insert(0, module_path) # Loop through all paths in system path, to pick up all potential locations for templates and static files. # Paths can get weird when the program is run from a different directory, or when the packaged exe is unpacked. for potential_path in sys.path: potential_template_path = potential_path if os.path.isdir(potential_template_path): # Insert the current plugin location to the system path, so bottle can find the templates bottle.TEMPLATE_PATH.insert(0, potential_template_path) potential_static_path = os.path.join(potential_path, 'static') if os.path.isdir(potential_static_path): STATIC_PATH = potential_static_path # webbrowser.open("http://localhost:8080") bottle.run(host='localhost', port=8080, debug=True)
Example #8
Source File: bottle.py From annotated-py-bottle with MIT License | 6 votes |
def error(code=500): # 出错处理 -- 写成装饰器函数. """ Decorator for error handler. Same as set_error_handler(code, handler).""" def wrapper(handler): # 包裹函数. set_error_handler(code, handler) return handler return wrapper # 调用 内嵌包裹函数. ############################################################################### ######################## 服务适配器部分 ########################################## # 1. web Server 这部分代码,多是导入现成的包,自己修改处理的代码,很少. # 2. 注意这种开发思想. # 3. 这里有 内嵌函数定义的应用,注意一下. ############################################################################### # Server adapter 服务适配器部分-定义 # 由全局的run()函数, 定位到此处.
Example #9
Source File: runner.py From puppet with MIT License | 6 votes |
def run(host='127.0.0.1', port=10086): from bottle import post, run, request, response @post('/puppet') def serve(): '''Puppet Web Trading Interface''' task = request.json if task: try: return getattr(acc, task.pop('action'))(**task) except Exception as e: response.bind(status=502) return {'puppet': str(e)} return {'puppet': '仅支持json格式'} print('Puppet version:', __version__) acc = Account() run(host=host, port=port)
Example #10
Source File: update_server.py From ethoscope with GNU General Public License v3.0 | 6 votes |
def run(self, handler): # pragma: no cover from cheroot import wsgi from cheroot.ssl import builtin self.options['bind_addr'] = (self.host, self.port) self.options['wsgi_app'] = handler certfile = self.options.pop('certfile', None) keyfile = self.options.pop('keyfile', None) chainfile = self.options.pop('chainfile', None) server = wsgi.Server(**self.options) if certfile and keyfile: server.ssl_adapter = builtin.BuiltinSSLAdapter( certfile, keyfile, chainfile) try: server.start() finally: server.stop() #############
Example #11
Source File: device_server.py From ethoscope with GNU General Public License v3.0 | 6 votes |
def run(self, handler): # pragma: no cover from cheroot import wsgi from cheroot.ssl import builtin self.options['bind_addr'] = (self.host, self.port) self.options['wsgi_app'] = handler certfile = self.options.pop('certfile', None) keyfile = self.options.pop('keyfile', None) chainfile = self.options.pop('chainfile', None) server = wsgi.Server(**self.options) if certfile and keyfile: server.ssl_adapter = builtin.BuiltinSSLAdapter( certfile, keyfile, chainfile) try: server.start() finally: server.stop() #############
Example #12
Source File: server.py From ethoscope with GNU General Public License v3.0 | 6 votes |
def run(self, handler): # pragma: no cover from cheroot import wsgi from cheroot.ssl import builtin self.options['bind_addr'] = (self.host, self.port) self.options['wsgi_app'] = handler certfile = self.options.pop('certfile', None) keyfile = self.options.pop('keyfile', None) chainfile = self.options.pop('chainfile', None) server = wsgi.Server(**self.options) if certfile and keyfile: server.ssl_adapter = builtin.BuiltinSSLAdapter( certfile, keyfile, chainfile) try: server.start() finally: server.stop() #############
Example #13
Source File: server.py From ethoscope with GNU General Public License v3.0 | 6 votes |
def force_device_backup(id): ''' Forces backup on device with specified id ''' results_dir = CFG.content['folders']['results']['path'] device_info = get_device_info(id) try: logging.info("Initiating backup for device %s" % device_info["id"]) backup_job = BackupClass(device_info, results_dir=results_dir) logging.info("Running backup for device %s" % device_info["id"]) backup_job.run() logging.info("Backup done for for device %s" % device_info["id"]) except Exception as e: logging.error("Unexpected error in backup. args are: %s" % str(args)) logging.error(traceback.format_exc())
Example #14
Source File: blog.py From anom-py with BSD 3-Clause "New" or "Revised" License | 5 votes |
def do_login(): username = request.forms.username password = request.forms.password user = User.login(username, password) if not user: return {"error": "Invalid credentials."} create_session(user) return redirect("/") # [END login] # [START run]
Example #15
Source File: guestbook.py From anom-py with BSD 3-Clause "New" or "Revised" License | 5 votes |
def delete(entry_id): entry = GuestbookEntry.get(entry_id) if not entry: return "<h1>Entry not found.</h1>" entry.delete() return redirect("/") # [END delete-route] # [START run]
Example #16
Source File: api_server.py From dwarf with Apache License 2.0 | 5 votes |
def run(self, handler): # Handle the TIME_WAIT state for quick server restarts WSGIServer.allow_reuse_address = 1 # Create the server and start it self.srv = WSGIServer((self.host, self.port), _HTTPRequestHandler) self.srv.set_app(self.app) try: self.srv.serve_forever() finally: self.srv.server_close()
Example #17
Source File: photobackup.py From server-bottle with GNU General Public License v2.0 | 5 votes |
def main(): """ Prepares and launches the bottle app. """ if (arguments['init']): init_config(arguments['<username>']) elif (arguments['run']): app = bottle.default_app() if 'HTTPPrefix' in config: app.mount(config['HTTPPrefix'], app) app.run(port=config['Port'], host=config['BindAddress']) elif (arguments['list']): print_list()
Example #18
Source File: photobackup.py From server-bottle with GNU General Public License v2.0 | 5 votes |
def init_config(username=None): """ Launch init.py script to create configuration file on user's disk. """ init.init(username) sys.exit("\nCreated, now launch PhotoBackup server with 'photobackup run'")
Example #19
Source File: bottle3.py From pyFileFixity with MIT License | 5 votes |
def run(app=None, server=WSGIRefServer, host='127.0.0.1', port=8080, interval=1, reloader=False, **kargs): """ Runs bottle as a web server. """ app = app if app else default_app() quiet = bool(kargs.get('quiet', False)) # Instantiate server, if it is a class instead of an instance if isinstance(server, type): server = server(host=host, port=port, **kargs) if not isinstance(server, ServerAdapter): raise RuntimeError("Server must be a subclass of WSGIAdapter") if not quiet and isinstance(server, ServerAdapter): # pragma: no cover if not reloader or os.environ.get('BOTTLE_CHILD') == 'true': print("Bottle server starting up (using %s)..." % repr(server)) print("Listening on http://%s:%d/" % (server.host, server.port)) print("Use Ctrl-C to quit.") print() else: print("Bottle auto reloader starting up...") try: if reloader and interval: reloader_run(server, app, interval) else: server.run(app) except KeyboardInterrupt: if not quiet: # pragma: no cover print("Shutting Down...") #TODO: If the parent process is killed (with SIGTERM) the childs survive...
Example #20
Source File: test_sm_rest_api.py From contrail-server-manager with Apache License 2.0 | 5 votes |
def launch_server_manager( listen_ip, listen_port, config_file): # Use a local logger.conf file for server manager debug and transaction logging settings. flexmock(server_mgr_main.ServerMgrlogger._ServerMgrlogger, log_file='./logger.conf') flexmock(server_mgr_main.ServerMgrTlog, log_file='./logger.conf') # mock all prints to go to a file #f = file('out.txt', 'w') #flexmock(sys, stdout=f) # Use local up address and unused port, instead of configured one to run SM. args_list = [] args_list += ['--listen_ip_addr', '%s' %(listen_ip)] args_list += ['--listen_port', '%s' %(listen_port)] args_list += ['--config_file', config_file] with mock.patch('server_mgr_cobbler.xmlrpclib.Server') as mock_server: with mock.patch('server_mgr_cobbler.subprocess') as mock_subprocess: vnc_server_mgr = server_mgr_main.VncServerManager(args_list) pipe_start_app = vnc_server_mgr.get_pipe_start_app() server_ip = vnc_server_mgr.get_server_ip() server_port = vnc_server_mgr.get_server_port() try: bottle.run(app=pipe_start_app,server = 'gevent', host=server_ip, port=server_port) except Exception as e: # cleanup gracefully print 'Exception error is: %s' % e vnc_server_mgr.cleanup() #end launch_api_server #Class for testing Server manager rest API calls for server, cluster and tag object
Example #21
Source File: bottle3.py From pyFileFixity with MIT License | 5 votes |
def run(self, handler): for sa in self.adapters: try: return sa(self.host, self.port, **self.options).run(handler) except ImportError: pass
Example #22
Source File: bottle3.py From pyFileFixity with MIT License | 5 votes |
def run(self, handler): import gunicorn.arbiter gunicorn.arbiter.Arbiter((self.host, self.port), 4, handler).run()
Example #23
Source File: bottle3.py From pyFileFixity with MIT License | 5 votes |
def run(self, handler): from diesel.protocols.wsgi import WSGIApplication app = WSGIApplication(handler, port=self.port) app.run()
Example #24
Source File: bottle3.py From pyFileFixity with MIT License | 5 votes |
def run(self, handler): from twisted.web import server, wsgi from twisted.python.threadpool import ThreadPool from twisted.internet import reactor thread_pool = ThreadPool() thread_pool.start() reactor.addSystemEventTrigger('after', 'shutdown', thread_pool.stop) factory = server.Site(wsgi.WSGIResource(reactor, thread_pool, handler)) reactor.listenTCP(self.port, factory, interface=self.host) reactor.run()
Example #25
Source File: bottle3.py From pyFileFixity with MIT License | 5 votes |
def run(self, handler): # pragma: no cover import tornado.wsgi import tornado.httpserver import tornado.ioloop container = tornado.wsgi.WSGIContainer(handler) server = tornado.httpserver.HTTPServer(container) server.listen(port=self.port) tornado.ioloop.IOLoop.instance().start()
Example #26
Source File: bottle3.py From pyFileFixity with MIT License | 5 votes |
def run(self, handler): # pragma: no cover import fapws._evwsgi as evwsgi from fapws import base evwsgi.start(self.host, self.port) evwsgi.set_base_module(base) def app(environ, start_response): environ['wsgi.multiprocess'] = False return handler(environ, start_response) evwsgi.wsgi_cb(('',app)) evwsgi.run()
Example #27
Source File: bottle3.py From pyFileFixity with MIT License | 5 votes |
def run(self, handler): # pragma: no cover from paste import httpserver from paste.translogger import TransLogger app = TransLogger(handler) httpserver.serve(app, host=self.host, port=str(self.port), **self.options)
Example #28
Source File: bottle3.py From pyFileFixity with MIT License | 5 votes |
def run(self, handler): # pragma: no cover from cherrypy import wsgiserver server = wsgiserver.CherryPyWSGIServer((self.host, self.port), handler) server.start()
Example #29
Source File: bottle3.py From pyFileFixity with MIT License | 5 votes |
def run(self, handler): # pragma: no cover from wsgiref.simple_server import make_server srv = make_server(self.host, self.port, handler) srv.serve_forever()
Example #30
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()