def test_no_hooks(self): @bottle.route(no_hooks=True) def test(): return 'nohooks' bottle.hook('before_request')(lambda: 1/0) bottle.hook('after_request')(lambda: 1/0) self.assertBody('nohooks', '/test')
def test_no_hooks(self): @bottle.route(no_hooks=True) def test(): return 'nohooks' bottle.hook('before_request')(lambda: 1 / 0) bottle.hook('after_request')(lambda: 1 / 0) self.assertBody('nohooks', '/test')
def test_no_hooks(self): @bottle.route(no_hooks=True) def test(): return "nohooks" bottle.hook("before_request")(lambda: 1 / 0) bottle.hook("after_request")(lambda: 1 / 0) self.assertBody("nohooks", "/test")
def import_routes(route_location): # import route module_obj = None __import__(route_location, globals(), locals()) module_obj = sys.modules[route_location] url_properties = { 'urls' : ['GET', 'POST', 'PUT', 'DELETE'], 'gets' : ['GET'], 'posts': ['POST'], 'puts' : ['PUT'], 'deletes': ['DELETE'] } # urls for url_property in url_properties: methods = url_properties[url_property] if hasattr(module_obj, url_property): for url_pair in getattr(module_obj, url_property): # address route_address = url_pair[0] slashed_url = add_begining_slash(add_trailing_slash(route_address)) unslashed_url = add_begining_slash(remove_trailing_slash(route_address)) # callback if len(url_pair)==1: route_callback = 'Undefined callback' else: route_callback = url_pair[1] if isinstance(route_callback, str): content = route_callback def wrapper(): return content route_callback = wrapper # default values name, apply_, skip, configs = None, None, None, {} # name if len(url_pair)>2: name = url_pair[2] # apply if len(url_pair)>3: apply_ = url_pair[3] # skip if len(url_pair)>4: skip = url_pair[4] # configs if len(url_pair)>5: configs = url_pair[5] # call the routes route(slashed_url, methods, route_callback, name, apply_, skip, **configs) route(unslashed_url, methods, route_callback, name, apply_, skip, **configs) # hooks if hasattr(module_obj, 'hooks'): for hook_pair in module_obj.hooks: hook(hook_pair[0])(hook_pair[1]) # errors if hasattr(module_obj, 'errors'): for error_pair in module_obj.errors: error(error_pair[0])(error_pair[1])
def route_instance(thing): for kw in dir(thing): attr = getattr(thing, kw) route = getattr(attr, '__route__', None) if route: bottle.route(route)(attr) hook = getattr(attr, '__hook__', None) if hook: bottle.hook(hook)(attr)
def __init__(self, bot, **kwargs): super().__init__(**kwargs) self.bot = bot self.file = os.path.join('data', 'ricedb.json') datadir = os.path.dirname(self.file) try: with open(self.file, 'r') as fd: self.update(json.load(fd)) except FileNotFoundError: # Database file itself doesn't need to exist on first run, it will be created on first write. if not os.path.exists(datadir): os.mkdir(datadir) self.bot.log.debug('Created {0}/ directory'.format(datadir)) try: self.config = self.bot.config[__name__] if not self.config.get('enable_http_server'): return host, port = self.config['http_host'], int( self.config['http_port']) except KeyError: host, port = '127.0.0.1', 8080 bottle.hook('before_request')(self.__strip_path) bottle.route('/')(self.__http_index) bottle.route('/<user>')(self.__http_index) bottle.route('/<user>/<key>')(self.__http_index) bottle_thread = threading.Thread( target=bottle.run, kwargs={ 'quiet': True, 'host': host, 'port': port }, name='{0} HTTP server'.format(__name__), daemon=True) bottle_thread.start() self.bot.log.info('{0} started on http://{1}:{2}'.format( bottle_thread.name, host, port))
def start(self): def log_all(): log_request(request, "{0} {1} ".format(request.method, request.fullpath)) hook('after_request')(log_all) try: config = yaml.load(open("config/development.yml", "r")) host = config.get("host", "127.0.0.1") port = config.get("port", 8080) server = config.get("server", "cherrypy") except Exception as e: log("Unable to load development config: {0}".format(e)) log("Continuing using the defaults.") host = "127.0.0.1" port = 8080 server = "cherrypy" run(app=self.get_app(), host=host, port=port, server=server)
def import_routes(route_location): # import route module_obj = None __import__(route_location, globals(), locals()) module_obj = sys.modules[route_location] # urls if hasattr(module_obj, 'urls'): for url_pair in module_obj.urls: slashed_url = add_trailing_slash(url_pair[0]) unslashed_url = remove_trailing_slash(url_pair[0]) route(slashed_url)(url_pair[1]) route(unslashed_url)(url_pair[1]) # hooks if hasattr(module_obj, 'hooks'): for hook_pair in module_obj.hooks: hook(hook_pair[0])(hook_pair[1]) # errors if hasattr(module_obj, 'errors'): for error_pair in module_obj.errors: error(error_pair[0])(error_pair[1])
def start(self): def log_all(): log_request( request, "{0} {1} ".format(request.method, request.fullpath) ) hook('after_request')(log_all) try: config = yaml.load(open("config/development.yml", "r")) host = config.get("host", "127.0.0.1") port = config.get("port", 8080) server = config.get("server", "cherrypy") except Exception as e: log("Unable to load development config: {0}".format(e)) log("Continuing using the defaults.") host = "127.0.0.1" port = 8080 server = "cherrypy" run(app=self.get_app(), host=host, port=port, server=server)
def __init__(self): self.app = default_app() self.db = yaml.load(open("config/database.yml", "r")) self.mongo_conf = self.db["mongo"] self.db = self.db["beaker"] self.main_conf = yaml.load(open("config/config.yml", "r")) self.db_uri = "%s://%s:%s@%s/%s" % ( self.db["adapter"], self.db["username"], self.db["password"], self.db["host"], self.db["database"] ) if "socket" in self.db and self.db["socket"]: log("Using unix socket for DB connection: %s" % self.db["socket"], logging.INFO) self.db_uri += "?unix_socket=%s" % self.db["socket"] session_opts = { "session.cookie_expires": True, "session.type": "ext:database", "session.url": self.db_uri, "session.lock_dir": "sessions/lock/", # "auto": True, "secret": self.main_conf["secret"] } def setup_request(): request.session = request.environ['beaker.session'] def log_all(): log_request(request, "%s %s " % (request.method, request.fullpath), logging.INFO) hook('before_request')(setup_request) hook('after_request')(log_all) self.wrapped = SessionMiddleware(self.app, session_opts) self.routes = {} self.api_routes = [] files = os.listdir("routes") files.remove("__init__.py") for _file in files: if _file.endswith(".py"): module = _file.rsplit(".", 1)[0] if module in self.main_conf.get("disabled-routes", []): log("Routes module '%s' is disabled - not loading." % module, logging.INFO) continue try: log("Loading routes module '%s'..." % module, logging.INFO) mod = __import__("routes.%s" % module, fromlist=["Routes"]) self.routes[module] = mod.Routes(self.wrapped, self) except Exception as e: log("Error loading routes module '%s': %s" % (module, e), logging.INFO) log("%s routes set up." % len(self.app.routes), logging.INFO)
global streaming_downloader global temp_dir global m3u8_path global m3u8_url global pool streaming_downloader = None pool = {} slices = {} BASE_DIR = os.path.dirname(os.path.abspath(__file__)) STATIC_PATH = os.path.join(BASE_DIR, 'static') hook('after_request') def set_unicode(): response.headers['Content-Type'] = 'application/json; charset=UTF-8' def to_static_url(path): global BASE_DIR static_url = os.path.join('/static', os.path.relpath(path, STATIC_PATH)) return static_url @route('/') def index(): global streaming_downloader if streaming_downloader: return redirect ('/main') else:
def kokoro_init(**kwargs): """ Start a server instance. This method blocks until the server terminates. :param app: WSGI application or target string supported by :func:`load_app`. (default: :func:`default_app`) :param server: Server adapter to use. See :data:`server_names` keys for valid names or pass a :class:`ServerAdapter` subclass. (default: `wsgiref`) :param host: Server address to bind to. Pass ``0.0.0.0`` to listens on all interfaces including the external one. (default: 127.0.0.1) :param port: Server port to bind to. Values below 1024 require root privileges. (default: 8080) :param reloader: Start auto-reloading server? (default: False) :param interval: Auto-reloader interval in seconds (default: 1) :param quiet: Suppress output to stdout and stderr? (default: False) :param options: Options passed to the server adapter. """ ################################################################################################### # kwargs arguments ################################################################################################### APPLICATION_PATH = kwargs.pop("application_path", "./applications" ) APP = kwargs.pop("app", bottle.app() ) SERVER = kwargs.pop("server", "kokoro" ) DEBUG = kwargs.pop("debug", True ) PORT = kwargs.pop("port", 8080 ) RELOADER = kwargs.pop("reloader", True ) HOST = kwargs.pop("host", "127.0.0.1" ) QUIET = kwargs.pop("quiet", False ) INTERVAL = kwargs.pop("interval", 1 ) PLUGINS = kwargs.pop("plugins", None ) RUN = kwargs.pop("run", True ) BASE_URL = kwargs.pop("base_url", '/' ) RUNTIME_PATH = kwargs.pop("runtime_path", '.runtime/' ) ################################################################################################### # parameters ################################################################################################### APPLICATION_PATH = add_trailing_slash(os.path.abspath(APPLICATION_PATH)) BASE_URL = add_trailing_slash(add_begining_slash(BASE_URL)) RUNTIME_PATH = add_trailing_slash(os.path.join(tempfile.gettempdir(), RUNTIME_PATH)) UNTRAILED_SLASH_RUNTIME_PATH = remove_trailing_slash(RUNTIME_PATH) APPLICATION_PACKAGE = os.path.split(remove_trailing_slash(APPLICATION_PATH))[-1] MPL_CONFIG_DIR_PATH = os.path.join(UNTRAILED_SLASH_RUNTIME_PATH,"mplconfigdir") # save BASE_URL and RUNTIME_PATH to os.environ os.environ['__KOKOROPY_BASE_URL__'] = BASE_URL os.environ['__KOKOROPY_RUNTIME_PATH__'] = RUNTIME_PATH os.environ['__KOKOROPY_APPLICATION_PATH__'] = APPLICATION_PATH ################################################################################################### # prepare runtime path ################################################################################################### print ("PREPARE RUNTIME PATH " + UNTRAILED_SLASH_RUNTIME_PATH) if not os.path.exists(UNTRAILED_SLASH_RUNTIME_PATH): os.makedirs(UNTRAILED_SLASH_RUNTIME_PATH) if not os.path.exists(MPL_CONFIG_DIR_PATH): os.makedirs(MPL_CONFIG_DIR_PATH) # set mplconfigdir for matplotlib if ('MPLCONFIGDIR' not in os.environ) or (not os.access(os.environ['MPLCONFIGDIR'], os.W_OK)): os.environ['MPLCONFIGDIR'] = MPL_CONFIG_DIR_PATH # point MPLCONFIGDIR to writable directory ################################################################################################### # get all kokoropy application ################################################################################################### # init application_list print ("INIT APPLICATION DIRECTORIES") application_list = [] for application in os.listdir(APPLICATION_PATH): if os.path.isfile(os.path.join(APPLICATION_PATH, application, "__init__.py")) and \ os.path.isfile(os.path.join(APPLICATION_PATH, application, "controllers", "__init__.py")): application_list.append(application) application_list = _sort_names(application_list) ################################################################################################### # get application controller modules ################################################################################################### # controller_dict_list is a dictionary with application name as key # and array of controller as value controller_dict_list = {} for application in application_list: for file_name in os.listdir(os.path.join(APPLICATION_PATH, application, "controllers")): # get application inside application"s controller file_name_segments = file_name.split(".") first_segment = file_name_segments[0] last_segment = file_name_segments[-1] if (first_segment == "__init__") or (not last_segment == "py"): continue module_name = inspect.getmodulename(file_name) if module_name is None: continue if not application in controller_dict_list: controller_dict_list[application] = [] controller_dict_list[application].append(module_name) ################################################################################################### # some predefined routes ################################################################################################### application_pattern = "|".join(application_list) kokoro_router = _Kokoro_Router() route(base_url("<path:re:(favicon.ico)>"))(kokoro_router.serve_assets) route(base_url("<application:re:"+application_pattern+">/assets/<path:re:.+>"))(kokoro_router.serve_assets) route(base_url("assets/<path:re:.+>"))(kokoro_router.serve_assets) hook('before_request')(kokoro_router.before_request) print("LOAD GLOBAL ROUTES") import_routes(APPLICATION_PACKAGE + ".routes") # exec("from "+APPLICATION_PACKAGE+".routes import *") ################################################################################################### # Load routes ################################################################################################### for application in application_list: if os.path.isfile(os.path.join(APPLICATION_PATH, application, "routes.py")): print("LOAD ROUTES : "+application) import_routes(APPLICATION_PACKAGE + ".routes") # exec("from "+APPLICATION_PACKAGE+"."+application+".routes import *") ################################################################################################### # Load Autoroute inside controller modules ################################################################################################### for application in controller_dict_list: for controller in controller_dict_list[application]: print("INSPECT CONTROLLER : "+application+".controllers."+controller) # import our controllers module_obj = None import_location = APPLICATION_PACKAGE+"."+application+".controllers."+controller __import__(import_location, globals(), locals()) module_obj = sys.modules[import_location] members = inspect.getmembers(module_obj, inspect.isclass) # determine if autoroute_controller exists autoroute_controller_found = False autoroute_controller_name = ""; Controller = None for member in members: # if find any descendant of Autoroute_Controller and not Autoroute_Controller itself if member[1] != Autoroute_Controller and issubclass(member[1], Autoroute_Controller): autoroute_controller_found = True autoroute_controller_name = member[0] Controller = member[1] break # skip if there is no autoroute_controller if not autoroute_controller_found: continue # make an instance of Default_Controller autoroute_controller = Controller() methods = inspect.getmembers(autoroute_controller, inspect.ismethod) # publish all methods with REST prefix (get, post, put and delete) _publish_methods(application, controller, "get", methods, [get] ) _publish_methods(application, controller, "post", methods, [post] ) _publish_methods(application, controller, "put", methods, [put] ) _publish_methods(application, controller, "delete", methods, [delete] ) # publish all methods with action prefix _publish_methods(application, controller, "action", methods, [route, get, post, put, delete] ) print("LOAD AUTOROUTE CONTROLLER : "+application+".controllers."+\ controller+"."+autoroute_controller_name) ################################################################################################### # add template & assets path ################################################################################################### TEMPLATE_PATH.append(APPLICATION_PATH) ################################################################################################### # run the application ################################################################################################### session_opts = { "session.type": "file", "session.data_dir": os.path.join(UNTRAILED_SLASH_RUNTIME_PATH,"session"), "session.auto": True, } app = beaker.middleware.SessionMiddleware(APP, session_opts) port = int(os.environ.get("PORT", PORT)) if RUN: if SERVER == 'kokoro': SERVER = KokoroWSGIRefServer(host=HOST, port=port) run(app=app, server=SERVER, reloader=RELOADER, host=HOST, port=port, quiet=QUIET, interval=INTERVAL, debug=DEBUG, plugins=PLUGINS, **kwargs) else: return app