def _setup(self): """install plugins and active services""" # active services for service_id, service in self._services: try: self._env.log.info("active service %s" % service_id) on_active = getattr(service, "on_active") on_active() except AttributeError: pass except Exception as exc: self._env.log.exception("active service %s failed:%s" % \ (service_id, unicode(exc))) # install plugins for plugin_id, plugin in self._plugins: try: self._env.log.info("install plugin %s" % plugin_id) install(plugin) except Exception as exc: self._env.log.exception("load plugin %s failed:%s" % \ (plugin_id, unicode(exc))) # actions for cls_name, cls_inst in self._action_classes.items(): try: self._env.log.info("active action class %s" % cls_name) on_active = getattr(cls_inst, "on_active") on_active() except AttributeError: pass except Exception as exc: self._env.log.exception("active action %s failed:%s" % \ (cls_name, unicode(exc)))
def start(server): config.init(server.upper()) from bottle_mysql import MySQLPlugin import controllers install(MySQLPlugin(**config.db_conf)) run(host="0.0.0.0", port=config.port, debug=True, reloader=True, server='twisted')
def run_serve(self, port=3000, debug=False): debuger = debug MiddlewareManager().add_pos_middleware(CygrpcLogMiddleware) _logging.info(f"starting http serve on port: {port}") bottle.install(EnableCors()) bottle.run(host='0.0.0.0', port=port, debug=debug, quiet=True, server='paste') exit(0)
def server(config, host="127.0.0.1"): install(SQLitePlugin(dbfile='ratings.db')) install(ConfigPlugin(config)) lInfo("server starting.") run(host=host, port=config["http_port"], debug=True, reloader=True) lInfo("server stopped.")
def main(): # Install plugins parser = argparse.ArgumentParser() parser.add_argument('action', help='run | init') parser.add_argument('--db', '-d', help='Database uri') parser.add_argument('--schema', '-s', help='Tanker Schema') parser.add_argument('--server', '-S', help='Wsgi server to use', default='wsgiref') parser.add_argument('--debug', '-D', action='store_true', help='Enable debug mode') cli = parser.parse_args() cfg = { 'db_uri': cli.db, 'schema': cli.schema, } install(TankerPlugin(cfg)) app = default_app() if cli.action == 'run': if cli.debug: app.add_hook('after_request', log) logger.setLevel('DEBUG') app.run(host='localhost', port=8080, server=cli.server, debug=cli.debug) elif cli.action == 'init': with connect(cfg): create_tables()
def main(av): cli_options = CliOptions(av[1:]) logging_level = logging.WARN if cli_options.debug: logging_level = logging.DEBUG elif cli_options.verbose: logging_level = logging.INFO logging.basicConfig(level=logging_level, format="[%(asctime)s][%(levelname)s]: %(message)s") logging.debug("Debug messages enabled") path_data = pathlib.Path(cli_options.data_dir) if not path_data.is_dir(): path_data = pathlib.Path(Defaults.DIR_SYS_DATA) / Defaults.PROGRAM_NAME if not path_data.is_dir(): logging.critical("No data directory detected") return 1 path_ui = path_data / "ui" / cli_options.user_interface if not path_ui.is_dir(): logging.critical("No such user interface detected: %s", cli_options.user_interface) return 1 path_cache = pathlib.Path(cli_options.ephemerals) if not path_cache.is_dir(): try: path_cache.mkdir(parents=True) except Exception as e: logging.warning("couldn't create the cache directory: %s", e) path_cache = pathlib.Path( Defaults.DIR_SYS_CACHE) / Defaults.PROGRAM_NAME if not path_cache.is_dir(): logging.critical("No cache directory detected") return 1 bottle.TEMPLATE_PATH = [path_ui / "templates"] # FIXME: the resources will be unpacked in the cache, but they are generated from the ui directory first bottle.app().resources = bottle.ResourceManager( str(path_ui / "static") + os.sep) bottle.app().resources.add_path(".") path_thumbnails = path_cache / "thumbnails" try: logging.debug("thumbnail directory: %s", path_thumbnails) path_thumbnails.mkdir(parents=True, exist_ok=True) except Exception as e: logging.critical("couldn't create the thumbnail directory: %s", e) return 1 bottle.install(MediaDatabasePlugin(cli_options.paths, path_thumbnails)) bottle.run(host=cli_options.host, port=cli_options.port, debug=cli_options.debug, reloader=cli_options.debug) return 0
def init_ldap() -> None: """Initialize the LDAP connection.""" ldap_url = os.environ.get("LDAP_URL", "ldap://localhost:389") logging.info("Initializing LDAP server at %s", ldap_url) ldap_server = ldap.initialize(ldap_url) ldap_injection_plugin = InjectionPlugin(value=ldap_server, keyword="ldap_server") bottle.install(ldap_injection_plugin)
def install(self, plugins=[]): third_party_plugin_dir = '/'.join([self.config.apppath, 'plugins']) third_party_plugin_module = '.'.join([ self.config.apppath.strip(os.path.sep).split(os.path.sep).pop(), 'plugins']) for plugin in plugins: name = ''.join([plugin.capitalize(), 'Plugin']) cls = getattr(lib.plugin, name, None) if not cls and os.path.isdir(third_party_plugin_dir): for plugin_file in os.listdir(third_party_plugin_dir): if not plugin_file.endswith('.py'): continue module = __import__( '.'.join([ third_party_plugin_module, os.path.splitext(plugin_file)[0]]), fromlist=[name]) cls = getattr(module, name, None) if cls: break if not cls: raise ImportWarning(name + ' is not found.') bottle.install(cls())
def start(self): # setup routing route("/display/brightness", method=['OPTIONS', 'POST'])(self.set_brightness) route("/mode", method=['OPTIONS', 'POST'])(self.set_mode) route("/moodlight/mode", method=['OPTIONS', 'POST'])(self.set_moodlight_mode) route("/text", method=['OPTIONS', 'POST'])(self.set_text) route("/gameframe", method=['OPTIONS', 'GET'])(self.get_gameframes) route("/gameframe", method=['OPTIONS', 'DELETE'])(self.delete_gameframe) route("/gameframe/next", method=['OPTIONS', 'POST'])(self.next_gameframe) route("/gameframe/current", method=['OPTIONS', 'POST'])(self.set_next_gameframe) get("/gameframe/<gameframe>")(self.get_gameframe) post("/gameframe/upload/<name>")(self.upload_gameframe) post("/gameframe")(self.select_gameframes) # run server install(EnableCors()) threading.Thread(target=run, kwargs=dict(host='127.0.0.1', port=8081, server=CustomWSGIRefServer, quiet=True)).start()
def install_plugins(config): plugins = config.plugins third_party_plugin_dir = '/'.join([config.apppath, 'plugins']) third_party_plugin_module = '.'.join([ config.apppath.strip(os.path.sep).split(os.path.sep).pop(), 'plugins' ]) for plugin in plugins: name = plugin.capitalize() + 'Plugin' cls = getattr(lib.plugin, name, None) if not cls and os.path.isdir(third_party_plugin_dir): for plugin_file in os.listdir(third_party_plugin_dir): if not plugin_file.endswith('.py'): continue module = __import__('.'.join([ third_party_plugin_module, os.path.splitext(plugin_file)[0] ]), fromlist=[name]) cls = getattr(module, name, None) if cls: break if not cls: raise ImportWarning(name + ' is not found.') bottle.install(cls())
def get_app(config): """ Get a Bottle app instance with all the routes set-up. :return: The built bottle app. """ get_session = database.init_db(config["database"], config["search_index"]) app = bottle.default_app() app.install(DatabasePlugin(get_session)) app.install(ConfigPlugin(config)) app.config.setdefault("canister.log_level", logging.root.level) app.config.setdefault("canister.log_path", None) app.config.setdefault("canister.debug", False) app.install(canister.Canister()) # Use DateAwareJSONEncoder to dump JSON strings # From http://stackoverflow.com/questions/21282040/bottle-framework-how-to-return-datetime-in-json-response#comment55718456_21282666. pylint: disable=locally-disabled,line-too-long bottle.install( bottle.JSONPlugin( json_dumps=functools.partial(json.dumps, cls=DateAwareJSONEncoder) ) ) # API v1 routes app.route("/api/v1/", "GET", api_routes.index_v1) app.route("/api/v1/time_to_places", "GET", api_routes.time_to_places_v1) app.route("/api/v1/flats", "GET", api_routes.flats_v1) app.route("/api/v1/flats/status/:status", "GET", api_routes.flats_by_status_v1) app.route("/api/v1/flat/:flat_id", "GET", api_routes.flat_v1) app.route("/api/v1/flat/:flat_id/status", "POST", api_routes.update_flat_status_v1) app.route("/api/v1/flat/:flat_id/notes", "POST", api_routes.update_flat_notes_v1) app.route("/api/v1/flat/:flat_id/notation", "POST", api_routes.update_flat_notation_v1) app.route("/api/v1/search", "POST", api_routes.search_v1) # Index app.route("/", "GET", lambda: _serve_static_file("index.html")) # Static files app.route("/favicon.ico", "GET", lambda: _serve_static_file("favicon.ico")) app.route( "/assets/<filename:path>", "GET", lambda filename: _serve_static_file("/assets/{}".format(filename)) ) app.route( "/img/<filename:path>", "GET", lambda filename: _serve_static_file("/img/{}".format(filename)) ) return app
def test_apply_to_get_route(self): """Test that session ids are not authenticated with non-post routes.""" database_mock = Mock() database_mock.sessions.find_one.return_value = None bottle.install(InjectionPlugin(database_mock, "database")) bottle.install(AuthenticationPlugin()) route = bottle.Route(bottle.app(), "/", "GET", self.route) self.assertEqual("route called", route.call())
def test_apply_plugin(self): """Test that the plugin can be applied to a route.""" def route(keyword): return keyword bottle.install(InjectionPlugin("value", "keyword")) route = bottle.Route(bottle.app(), "/", "GET", route) self.assertEqual("value", route.call())
def main(): config = get_config() tplugin = TermsPlugin(config) install(tplugin) host = 'http_host' in config and config['http_host'] or 'localhost' port = 'http_port' in config and config['http_port'] or 8080 debug = 'debug' in config and config.getboolean('debug') or False run(host=host, port=port, debug=debug)
def test_apply_plugin_to_route_that_does_not_take_keyword(self): """Test that the plugin can be applied to a route.""" def route(): return "route" bottle.install(InjectionPlugin("value", "keyword")) route = bottle.Route(bottle.app(), "/", "GET", route) self.assertEqual("route", route.call())
def start_server(cfg): bottle.install(log_to_logger) # remember to remove reloader=True and debug(True) when you move your # application from development to a productive environment bottle.debug(bool(cfg["SERVER_DEBUG"])) bottle.run(reloader=bool(cfg["SERVER_DEBUG"]), host=str(cfg["SERVER_HOST"]), port=int(cfg["SERVER_PORT"]))
def main(port): #Beaker options session_opts = { 'session.type': 'file', 'session.cookie_expires': True, 'session.data_dir': './.cache', 'session.auto': True } #Debug mode ? if port != 80 and port != 443: #Sqlite db file #mydbfile_solarmax = os.path.join(ROOT_PATH, "Solarmax_data2.s3db") #mydbfile_teleinfo = os.path.join(ROOT_PATH, "../teleinfo/Teleinfo_data.s3db") mydbfile_solarmax = os.path.join(ROOT_PATH, "../data/Solarmax_data2.s3db") mydbfile_teleinfo = os.path.join(ROOT_PATH, "../data/Teleinfo_data.s3db") access_log_file = 'access.log' #Run http test server on given port myserver = 'wsgiref' else: #Sqlite db file mydbfile_solarmax = DB_FILE_SOLAR mydbfile_teleinfo = DB_FILE_TELEINFO #Run CherryPy http or https server if port == 80: myserver = 'cherrypy' access_log_file = VAR_LOG_ACCESS elif port == 443: myserver = SSLCherryPyServer access_log_file = VAR_LOG_ACCESS_SSL #Create default bottle application app = default_app() myapp = SessionMiddleware(app, session_opts) handlers = [ TimedRotatingFileHandler(access_log_file, 'd', 7, 90), ] loggingapp = WSGILogger(myapp, handlers, ApacheFormatter()) #Plugins : SQLitePlugin give a connection in each functions with a db parameter install(SQLitePlugin(dbfile=mydbfile_solarmax)) plugin2 = SQLitePlugin(dbfile=mydbfile_teleinfo, keyword='db2') plugin2.name = "sqlite2" install(plugin2) #Run server run(app=loggingapp, host='0.0.0.0', port=port, server=myserver, reload=True)
def init_swagger(): this_dir = os.path.dirname(os.path.abspath(__file__)) with open("{}/swagger/swagger.yml".format(this_dir)) as f: swagger_def = yaml.load(f) swagger_plugin = SwaggerPlugin(swagger_def, ignore_undefined_api_routes=True, serve_swagger_ui=True) install(swagger_plugin)
def test_apply_invalid_session(self): """Test that session ids are authenticated.""" database_mock = Mock() database_mock.sessions.find_one.return_value = None bottle.install(InjectionPlugin(database_mock, "database")) bottle.install(AuthenticationPlugin()) route = bottle.Route(bottle.app(), "/", "POST", self.route) with patch("logging.warning", Mock()): # Suppress logging self.assertEqual(dict(ok=False), route.call())
def setUp(self): """Override to set up a mock database and install the plugins.""" logging.disable() self.mock_database = Mock() self.mock_database.reports_overviews.find_one.return_value = dict( _id="id") self.success = dict(ok=True) bottle.install(InjectionPlugin(self.mock_database, "database")) bottle.install(AuthPlugin())
def main(): args = configure_cli_args() config_file = os.path.expanduser(args.config) data_dir = os.path.expanduser(args.data) modules_dir = os.path.expanduser(args.modules) if args.install: sys.exit(install(data_dir=data_dir, config_file=config_file, modules_dir=modules_dir)) config = load_yaml(config_file) config = setup_config(config, data_dir) if not check_config(config): sys.exit(1) description = config['description'] if 'description' in config else '' bot = commands.Bot(command_prefix=config['command'], description=description, formatter=BotHelpFormatter()) @bot.event async def on_ready(): logger.info('Logged in as %s (%s)' % (bot.user.name, bot.user.id)) logger.info('Use this link to add bot to server: ' 'https://discordapp.com/oauth2/authorize?&client_id=%s&scope=bot' % config['api']['id']) mod_config = { 'db': sqlite3.connect(os.path.join(data_dir, 'db.sqlite3'), detect_types=sqlite3.PARSE_DECLTYPES) } if 'parameters' in config: mod_config['paremeters'] = config['parameters'] load_core_module(bot, mod_config) sys.path.append(modules_dir) if 'modules' in config: for module in config['modules']: try: logger.info('Loading module %s' % module) mod = importlib.import_module(module) for action in config['modules'][module]: try: logger.info('Executing module action %s' % action) getattr(mod, action)(bot, mod_config) except Exception as e: logger.error('Could not execute module\'s %s action %s: %s' % (module, action, e)) except ImportError as e: logger.error('Error loading module %s: %s' % (module, e.msg)) if config['api_key']: api_plugin.set_api_key(config['api_key']) bottle.install(api_plugin) Thread(target=bottle.run, kwargs={'host': args.api_host, 'port': args.api_port}).start() bot.run(config['api']['token'])
def init(): conf = context.get_conf() host = conf.get('rest', 'host') port = conf.get_int('rest', 'port') install(error_handler) restp = threading.Thread(target=run,kwargs={'host': host, 'port': port, 'quiet': True}) restp.setDaemon(True) restp.start()
def init(): db.connect() db.create_tables([Report]) if not db.is_closed(): db.close() # Use DateAwareJSONEncoder to dump JSON strings # From http://stackoverflow.com/questions/21282040/bottle-framework-how-to-return-datetime-in-json-response#comment55718456_21282666. pylint: disable=locally-disabled,line-too-long bottle.install( bottle.JSONPlugin(json_dumps=functools.partial( json.dumps, cls=DateAwareJSONEncoder)))
def production_run(config, reloader=False): lf = lambda: new_library(config, True) l = lf() l.database.create() logger.info("starting production server for library '{}' on http://{}:{}".format(l.name, l.host, l.port)) install(LibraryPlugin(lf)) return run(host=l.host, port=l.port, reloader=reloader)
def serve() -> None: """Connect to the database and start the application server.""" logging.getLogger().setLevel(logging.INFO) bottle.BaseRequest.MEMFILE_MAX = 1024 * 1024 # Max size of POST body in bytes database_url = os.environ.get("DATABASE_URL", "mongodb://*****:*****@localhost:27017") database = pymongo.MongoClient(database_url).quality_time_db logging.info("Connected to database: %s", database) logging.info("Measurements collection has %d measurements", database.measurements.count_documents({})) injection_plugin = InjectionPlugin(value=database, keyword="database") bottle.install(injection_plugin) import_datamodel(database) import_example_reports(database) bottle.run(server="gevent", host='0.0.0.0', port=8080, reloader=True)
def main(): get_env('INFRABOX_SERVICE') get_env('INFRABOX_VERSION') get_env('INFRABOX_DATABASE_HOST') get_env('INFRABOX_DATABASE_USER') get_env('INFRABOX_DATABASE_PASSWORD') get_env('INFRABOX_DATABASE_PORT') get_env('INFRABOX_DATABASE_DB') connect_db() # Wait until db is ready install(InfraBoxPostgresPlugin()) run(host='0.0.0.0', port=8081)
def main(): get_env('INFRABOX_VERSION') get_env('INFRABOX_DATABASE_DB') get_env('INFRABOX_DATABASE_USER') get_env('INFRABOX_DATABASE_PASSWORD') get_env('INFRABOX_DATABASE_HOST') get_env('INFRABOX_DATABASE_PORT') get_env('INFRABOX_GITHUB_WEBHOOK_SECRET') connect_db() # Wait until DB is ready install(InfraBoxPostgresPlugin()) run(host='0.0.0.0', port=8080)
def start(): parser = ArgumentParser(prog=sys.argv[0], description="Pollux'NZ City configurator") parser.add_argument("-V", '--version', action='version', version="%(prog)s version 0") parser.add_argument("-D", "--debug", dest="debug", action="store_true", default=False, help="Debug mode") parser.add_argument( "-p", "--path", dest="path", default="/etc/pollux", help='path to configuration directory. e.g. /etc/pollux/') parser.add_argument("-l", "--lib", dest="lib_path", default="/usr/lib/pollux", help='Directory where the modules lay') # HOST ARGUMENT parser.add_argument("-H", "--host", dest="host", default='0.0.0.0', help='Host to serve the web application on.') # PORT ARGUMENT parser.add_argument( "-P", "--port", dest="port", default='8080', help='Port to be used for serving the web application.') args = parser.parse_args(sys.argv[1:]) TEMPLATE_PATH.insert(0, pollux.views.__path__[0]) config = Configuration(args.path + "/", args.lib_path) sensors = Sensors(args.path + "/") install(config) install(sensors) return args
def server(config, host="127.0.0.1"): """ start the server part of avrateNG """ install(SQLitePlugin(dbfile='ratings.db')) install(ConfigPlugin(config)) lInfo("server starting.") run(host=host, port=config["http_port"], debug=False, reloader=False, fast=False) lInfo("server stopped.")
def run_rest_service(session_maker, args): if args.rollbar_token: if not ROLLBAR_SUPPORT: logger.error('Rollbar is not installed') return rbr = RollbarBottleReporter(access_token=args.rollbar_token, environment=args.rollbar_env) bottle.install(rbr) app.config['session_maker'] = session_maker app.config['allow_shutdown'] = args.allow_shutdown if args.debug: app.catchall = False app.run(host='0.0.0.0', port=args.port, server='gevent', debug=args.debug)
def setup(db, base_url=URL, paste_variable=VAR): global URL, VAR URL = base_url VAR = paste_variable log.warn('Using sqlite database in %s', db) if not os.path.isfile(db): import sqlite3 conn = sqlite3.connect(db) c = conn.cursor() c.execute('''CREATE TABLE IF NOT EXISTS pastes (id VARCHAR(8) UNIQUE, ip VARCHAR(15), created VARCHAR(26), content TEXT);''') conn.commit() conn.close() bottle.install(SQLitePlugin(dbfile=db))
def runserver(): from views import auth, user, rest, member, admin, base, analysis from util.plugins import set_user from bottle import install @route('/static/<path:path>', name='static') def static_files(path): return static_file(path, root='./static/') @route('/favicon.ico', name='static') def favicon(): return static_file('img/favicon.png', root='./static/') bottle.install(set_user) bottle.debug(True) bottle.run(app=sapp, reloader=True, host='0.0.0.0', port=8080)
def _run(host, port, redis, unregistered_key, reloader=False, **kwargs): import redis as rds pool = rds.ConnectionPool(host=redis['host'], port=redis['port'], db=0) rds = rds.Redis(connection_pool=pool) # This is the key that can be distributed publically. It is only to # keep bots and spiders from sucking up a bunch of numbers. rds.set("assignment_class:" + unregistered_key, 'unregistered') install(RedisPlugin(pool)) print host, port return run(host=host, port=port, reloader=reloader, server='paste')
def plugin(pre_func=None, post_func=None): def Plugin(callback): def wrapper(*args, **kwargs): if pre_func: pre_func() body = callback(*args, **kwargs) if post_func: post_func() return body return wrapper bottle.install(Plugin)
def main(): global db, conf p = argparse.ArgumentParser(description='Run the NFLfan web interface.') p.add_argument('--config', metavar='DIR', default='', help='Configuration directory.') p.add_argument('--debug', action='store_true', help='Enable Bottle\'s debug mode.') p.add_argument('--reload', action='store_true', help='Enable Bottle\'s reloading functionality.') p.add_argument('--port', type=int, default=8080) p.add_argument('--host', default='localhost') p.add_argument('--server', default='wsgiref', help='The web server to use. You only need to change this ' 'if you\'re running a production server.') p.add_argument('--available-servers', action='store_true', help='Shows list of available web server names and quits.') args = p.parse_args() if args.available_servers: for name in sorted(bottle.server_names): try: __import__(name) print(name) except: pass sys.exit(0) bottle.TEMPLATE_PATH.insert(0, path.join(web_path, 'tpl')) db = nfldb.connect() conf = nflfan.load_config(providers=nflfan.builtin_providers, file_path=args.config) builtins['db'] = db builtins['conf'] = conf bottle.install(exec_time) bottle.run(server=args.server, host=args.host, port=args.port, debug=args.debug, reloader=args.reload)
def main(host, port, quiet): # Initialize database conn = sqlite3.connect(db_file.name) # or use :memory: to put it in RAM cursor = conn.cursor() cursor.execute(""" CREATE TABLE event_log ( event_type TEXT, resource_name TEXT, event TEXT, event_time TIMESTAMP DEFAULT (datetime('now','localtime')) ) """) # Install sqlite bottle plugin install(SQLitePlugin(dbfile=db_file.name)) run(host=host, port=port, quiet=quiet)
def make_app(): def create_session(*args, **kw): return Session app = bottle.app() app = SessionMiddleware(app, session_opts) engine = init() engine.echo = True bottle.install(SQLAlchemyPlugin(engine, create_session=create_session)) bottle.install(AuthPlugin(app, engine, create_session=create_session)) app_stack.vars = {'_': _, 'time': time} app_stack.view = partial(view, **app_stack.vars) app_stack.template = partial(template, **app_stack.vars) from trombi import views return app
def main(): """ Program entry point. """ parser = argparse.ArgumentParser() parser.add_argument('-a', '--address', default='127.0.0.1', help='The address on which to listen') parser.add_argument('-p', '--port', default=8080, help='The port on which to listen') parser.add_argument('-d', '--debug', action='store_true', help='Run in debug mode') parser.add_argument('path', type=str, help='Path to the database file') args = parser.parse_args(sys.argv[1:]) install(SQLitePlugin(dbfile=args.path)) run(host=args.address, port=args.port, debug=args.debug)
def local_run(config, reloader=False): global stoppable_wsgi_server_run stoppable_wsgi_server_run = None debug() lf = lambda: new_library(config, True) l = lf() l.database.create() logger.info("starting local server for library '{}' on http://{}:{}".format(l.name, l.host, l.port)) install(LibraryPlugin(lf)) return run(host=l.host, port=l.port, reloader=reloader)
def local_debug_run(config): debug() port = config["port"] if config["port"] else 7979 host = config["host"] if config["host"] else "localhost" logger.info("starting debug server on http://{}:{}".format(host, port)) lf = lambda: new_library(config, True) l = lf() l.database.create() install(LibraryPlugin(lf)) return run(host=host, port=port, reloader=True, server="stoppable")
def start(): parser = ArgumentParser(prog=sys.argv[0], description="Pollux'NZ City configurator") parser.add_argument("-V", '--version', action='version', version="%(prog)s version 0") parser.add_argument("-D", "--debug", dest="debug", action="store_true", default=False, help="Debug mode") parser.add_argument("-p", "--path", dest="path", default="/etc/pollux", help='path to configuration directory. e.g. /etc/pollux/') parser.add_argument("-l", "--lib", dest="lib_path", default="/usr/lib/pollux", help='Directory where the modules lay') # HOST ARGUMENT parser.add_argument("-H", "--host", dest="host", default='0.0.0.0', help='Host to serve the web application on.') # PORT ARGUMENT parser.add_argument("-P", "--port", dest="port", default='8080', help='Port to be used for serving the web application.') args = parser.parse_args(sys.argv[1:]) TEMPLATE_PATH.insert(0,pollux.views.__path__[0]) config = Configuration(args.path+"/",args.lib_path) sensors = Sensors(args.path+"/") install(config) install(sensors) return args
def test_run(config): """Run method to be called from unit tests.""" from bottle import run, debug # @UnresolvedImport debug() lf = lambda: new_library(config, True) l = lf() l.database.create() global_logger.info( "Starting test server on http://{}:{}".format(l.host, l.port)) global_logger.info("Library at: {}".format(l.database.dsn)) install(LibraryPlugin(lf)) return run(host=l.host, port=l.port, reloader=False, server='stoppable')
def start_server(self, host, port): self._bottle_server = StoppableWSGIRefServer(host=host, port=port) hb = Heartbeat() install(partial(local_variable_plugin, { 'cfg':self._cfg, 'heartbeat': hb, 'server' : self, 'download_manager' : self._download_manager, })) hb_monitor = HeartbeatMonitor(hb, self.SHUTDOWN_TIMEOUT, self._on_heartbeat_timeout) hb_monitor.monitor() run(server=self._bottle_server) self._download_manager.stop() hb_monitor.stop() _save_cfg(self._cfg)
def test_run(config): '''Run method to be called from unit tests''' from bottle import run, debug #@UnresolvedImport debug() port = config['port'] if config['port'] else 7979 host = config['host'] if config['host'] else 'localhost' logger.info("starting test server on http://{}:{}".format(host, port)) lf = lambda: new_library(config, True) l = lf() l.database.create() install(LibraryPlugin(lf)) return run(host=host, port=port, reloader=False, server='stoppable')
def test_run(config): """Run method to be called from unit tests""" from bottle import run, debug # @UnresolvedImport debug() port = config["port"] if config["port"] else 7979 host = config["host"] if config["host"] else "localhost" lf = lambda: new_library(config, True) l = lf() l.database.create() logger.info("Starting test server on http://{}:{}".format(host, port)) logger.info("Library at: {}".format(l.database.dsn)) install(LibraryPlugin(lf)) return run(host=host, port=port, reloader=False, server="stoppable")
def run(self): reload_js = dedent('''\ <script type="text/javascript"> $.ajaxSetup({cache: false}) // drop browser cache for refresh $(document).ready(function() { $.ajax({ type: "GET", async: true, cache: false, url: location.protocol + "//" + location.host + "/_svwait", success: function() {window.location.reload(true)} }) }) </script>''') def after_request(response): '''Add reload javascript and remove googleapis fonts''' r = response if not r.content_type.startswith('text/'): return r body = b''.join(r).decode('utf-8') r.close() if r.content_type.startswith('text/html'): body = re.sub(r'(</head>)', r'{}\1'.format(reload_js), body, flags=re.IGNORECASE) if r.content_type.startswith('text/css'): body = re.sub(r'@import url\(.+fonts.googleapis.com.+\);', '', body, flags=re.IGNORECASE) r.headers['Content-Length'] = len(body) r.body = body return r @get('<path:path>') def serve_static(path): path = path + '/index.html' if path.endswith('/') else path response = static_file(path, root=self.path) return after_request(response) @get('/_svwait') def wait_server_event(): '''Block long polling javascript until reload event''' self.reload_ev.wait() self.reload_ev.clear() install(log_to_logger) run(host=self.host, port=int(self.port), quiet=True, server='gevent')
def main(): global db, conf p = argparse.ArgumentParser( description='Run the NFLfan web interface.') p.add_argument('--config', metavar='DIR', default='', help='Configuration directory.') p.add_argument('--debug', action='store_true', help='Enable Bottle\'s debug mode.') p.add_argument('--reload', action='store_true', help='Enable Bottle\'s reloading functionality.') p.add_argument('--port', type=int, default=8080) p.add_argument('--host', default='localhost') p.add_argument('--server', default='wsgiref', help='The web server to use. You only need to change this ' 'if you\'re running a production server.') p.add_argument('--available-servers', action='store_true', help='Shows list of available web server names and quits.') args = p.parse_args() if args.available_servers: for name in sorted(bottle.server_names): try: __import__(name) print(name) except: pass sys.exit(0) bottle.TEMPLATE_PATH.insert(0, path.join(web_path, 'tpl')) db = nfldb.connect() conf = nflfan.load_config(providers=nflfan.builtin_providers, file_path=args.config) builtins['db'] = db builtins['conf'] = conf bottle.install(exec_time) bottle.run(server=args.server, host=args.host, port=args.port, debug=args.debug, reloader=args.reload)
def __init__(self, datebase_name, static_file_path=None, data_dir='./data', loggly_token=None): cork_dir = os.path.join(data_dir, 'cork') beaker_dir = os.path.join(data_dir, 'beaker') bottle.TEMPLATE_PATH.insert(0,'webapi/views/') #vars which must be visible across all webapi modules shared.static_dir = static_file_path shared.plug = bottle.ext.mongo.MongoPlugin(uri="localhost", db=datebase_name, json_mongo=True) #install mongo plugin for root app install(shared_state.plug) #check if cork files exists cork_files = ['users.json', 'roles.json', 'register.json'] if not set(cork_files).issubset(set(os.listdir(cork_dir))): #if not, create them logger.info('Cork authentication files not found, creating new files.') shared.auth = self.populate_conf_directory(cork_dir) else: shared.auth = Cork(cork_dir) #admin depends on shared.auth import admin #import and mount api version 1 (stable) from webapi.api.v1 import app as api_v1 mount('/api/v1/', api_v1.app) #import and mount development version (unstable) from webapi.api.d import app as api_d mount('/api/d/', api_d.app) #must be imported AFTER mounts. if shared.static_dir is not None: import default_routes #wrap root app in beaker middleware session_opts = { 'session.type': 'file', 'session.cookie_expires': False, 'session.data_dir': beaker_dir, 'session.auto': True, #set secure attribute on cookie 'session.secure': True } self.app = bottle.app() if loggly_token: self.app = Loggly(bottle.app(), loggly_token) self.app = SessionMiddleware(self.app, session_opts) root_app = bottle.app() #setup logging hooks @root_app.hook('before_request') @api_d.app.hook('before_request') @api_v1.app.hook('before_request') def log_request(): user_agent = "" if 'HTTP_USER_AGENT' in bottle.request.environ: user_agent = bottle.request.environ['HTTP_USER_AGENT'] if 'REMOTE_ADDR' in bottle.request.environ: remote_addr = bottle.request.environ['REMOTE_ADDR'] else: remote_addr = "" if 'beaker.session' in bottle.request.environ: session = bottle.request.environ.get('beaker.session') username = session.get('username', None) else: username = "******" logger.info("[{0}/{1}] {2} {3} ({4})".format(remote_addr, username, request.method, request.fullpath, user_agent)) def return_text(self, e): return e.status #make sure error pages for API are pure text api_d.app.default_error_handler = types.MethodType(return_text, self) api_v1.app.default_error_handler = types.MethodType(return_text, self)
from bottle import get, post, put, request, response, HTTPResponse from bottle import install from bottle_mongo import MongoPlugin from bson.objectid import ObjectId from pprint import pprint import validictory install(MongoPlugin(uri='localhost', db='mydatabase', json_mongo=True)) secret_key = 84251450 semesters = ['SPRING', 'SUMMER', 'FALL', 'WINTER'] # Schema for json Schedule object schedule_schema = { 'type': 'object', 'properties': { 'semester': {'type': 'string', 'enum': semesters, 'required': False}, 'year': {'type': 'integer', 'required': False}, 'user_id': {'type': 'any', 'required': False}, 'courses': { 'type': 'array', 'items': {'type': [ { 'type':'object', 'properties': { 'name': {'type': 'string'}, 'number': {'type': 'integer'}, 'dept': {'type': 'string'}, 'description': {'type': 'string'}, }
from bottle import route, install, template, run from bottle_sqlite import SQLitePlugin install(SQLitePlugin(dbfile='rest.db')) @route('/show/<post_id:int>') def show(db, post_id): c = db.execute('SELECT usuario, password FROM alunos WHERE id = ?', (post_id,)) row = c.fetchone() print row['usuario'] return template('show_post', usuario=row['usuario'], password=row['password']) run(reloader=True, debug=True, host="localhost", port=8007)
engine = create_engine(settings.DATABASE_CONNECTION_STRING, echo=True) create_session = sessionmaker(bind=engine) # set up the sqlalchemy plugin sqlalchemy_plugin = sqlalchemy.Plugin( engine, AlchemyBase.metadata, keyword='db', create=True, commit=True, use_kwargs=False ) # set up the bottle app install(sqlalchemy_plugin) class Excuse(AlchemyBase): __tablename__ = "excuses" id = Column(Integer, primary_key=True) excuse = Column(String, nullable=False) published = Column(Boolean, nullable=False, default=False) username = Column(String, nullable=False, default="admin") team_id = Column(String, nullable=True, default=None) def __init__(self, username, excuse): self.username = username self.excuse = excuse
# Attempt to serialize, raises exception on failure try: json_response = dumps(rv) except Exception as e: r = capture_return_exception(e) json_response = dumps(r) # Set content type only if serialization succesful response.content_type = "application/json" return json_response return wrapper install(AllJSONPlugin()) @error(404) @CaptureException def error404(error): raise exc.NotFound("For url: {}".format(repr(request.url))) @error(500) def error500(error): raise exc.InternalError("For Url: {}".format(repr(request.url))) @hook("after_request") def enable_cors():
import bottle import os import yaml from bottle_swagger import SwaggerPlugin this_dir = os.path.dirname(os.path.abspath(__file__)) with open("{}/swagger.yml".format(this_dir)) as f: swagger_def = yaml.load(f) bottle.install(SwaggerPlugin(swagger_def)) @bottle.get('/thing') def hello(): return {"id": "1", "name": "Thing1"} @bottle.get('/thing/<thing_id>') def hello(thing_id): return {"id": thing_id, "name": "Thing{}".format(thing_id)} @bottle.get('/thing_query') def hello(): thing_id = bottle.request.query['thing_id'] return {"id": thing_id, "name": "Thing{}".format(thing_id)} @bottle.get('/thing_header') def hello(): thing_id = bottle.request.headers['thing_id']
return "word not known" @bottle.route("/words.json") def words_json(pyborg): return {"words": pyborg.settings.num_words, "contexts": pyborg.settings.num_contexts, "lines": len(pyborg.lines)} @bottle.route("/commands.json") def commands_json(pyborg): return pyborg.commanddict @bottle.route("/logging-level", method="POST") def set_log_level(): # when we drop 2 support this can use strings instead of the enums levels = {"DEBUG": logging.DEBUG, "INFO": logging.INFO, "WARNING": logging.WARNING, "ERROR": logging.ERROR, "CRITICAL": logging.CRITICAL} target = levels[request.POST.get("level").upper()] logger.setLevel(target) if __name__ == '__main__': logging.basicConfig(level=logging.INFO) folder = click.get_app_dir("Pyborg") brain_path = os.path.join(folder, "brains", "current.pyborg.json") bottle.install(BottledPyborg(brain_path=brain_path)) bottle.run(host="localhost", port=2001, reloader=True)
import feedparser, json, bottle import lxml.html import xml.etree.ElementTree as ET from datetime import datetime from bottle import route, run, view, install, redirect, hook, request, response, abort, static_file from peewee import * from time import mktime class CustomJsonEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, datetime): return str(obj.strftime("%Y-%m-%d %H:%M:%S")) return json.JSONEncoder.default(self, obj) install(bottle.JSONPlugin(json_dumps=lambda s: json.dumps(s, cls=CustomJsonEncoder))) db = SqliteDatabase('database.db') class BaseModel(Model): class Meta: database = db class Channel(BaseModel): title = TextField() updated = DateTimeField(default = datetime(1900, 1, 1)) url = TextField(unique = True) icon = TextField(default = '/static/feed.png') def update_feed(self): feed = feedparser.parse(self.url) feed_updated = datetime(3000, 1, 1)