def __init__(self, name, dal, apis, mailer, *args, **kwargs): Flask.__init__(self, name, *args, **kwargs) self.dal = dal self.apis = apis self.mailer = mailer self._setup_routes()
def __init__(self, config): Flask.__init__(self, __name__) # TODO: deal with envvar and pyfile self.config.from_object(config) # Initialise helpers and services db.init_app(self) mail.init_app(self) # Babel babel.init_app(self) babel.localeselector(get_locale) # Assets (bundles are defined in the templates) assets = Environment(self) # Initialise filters init_filters(self) init_auth(self) from .apps.crm.frontend import CRM crm = CRM(self) self.register_blueprints() # Must come after all entity classes have been declared. self.register_services()
def __init__(self, *args, **kwargs): if not args: kwargs.setdefault('import_name', __name__) Flask.__init__(self, template_folder= "%s/templates" % dirname(__file__), *args, **kwargs) self.bs = Bootstrap(self) self.nav = Navigation() self.nav.init_app(self) self.nav.Bar('top', [ self.nav.Item('Home', 'index'), self.nav.Item('Responsables', 'responsables'), self.nav.Item('Usuarios', 'usuarios'), self.nav.Item('Impresoras', 'impresoras'), self.nav.Item('Impresiones', 'impresiones'), ]) # register the routes from the decorator for route, fn in registered_routes.items(): partial_fn = partial(fn, self) partial_fn.__name__ = fn.__name__ self.route(route)(partial_fn)
def __init__(self, *args, **kwds): self.startup_token = kwds.pop('startup_token', None) Flask.__init__(self, *args, **kwds) self.root_path = SAGENB_ROOT # I think it would make more sense just to have one /data/ path and not do one for every kind of file self.add_static_path('/data', os.path.join(DATA)) # this one is special though since it points to SAGE_ROOT self.add_static_path('/java/jmol', os.path.join(os.environ["SAGE_ROOT"], "local", "share", "jmol")) import mimetypes mimetypes.add_type('text/plain', '.jmol') mimetypes.add_type('font/opentype', '.otf') mimetypes.add_type('application/font-woff', '.woff') ####### # Doc # ####### #These "should" be in doc.py DOC = os.path.join(SAGE_DOC, 'output', 'html', 'en') self.add_static_path('/pdf', os.path.join(SAGE_DOC, 'output', 'pdf')) self.add_static_path('/doc/static', DOC)
def __init__(self, *args, **kwds): self.startup_token = kwds.pop('startup_token', None) Flask.__init__(self, *args, **kwds) self.session_interface = OldSecureCookieSessionInterface() self.config['SESSION_COOKIE_HTTPONLY'] = False self.root_path = SAGENB_ROOT self.add_static_path('/css', os.path.join(DATA, "sage", "css")) self.add_static_path('/images', os.path.join(DATA, "sage", "images")) self.add_static_path('/javascript', DATA) self.add_static_path('/static', DATA) self.add_static_path('/java', DATA) self.add_static_path('/java/jmol', os.path.join(os.environ["SAGE_ROOT"],"local","share","jmol")) import mimetypes mimetypes.add_type('text/plain','.jmol') ####### # Doc # ####### #These "should" be in doc.py DOC = os.path.join(SAGE_DOC, 'output', 'html', 'en') self.add_static_path('/pdf', os.path.join(SAGE_DOC, 'output', 'pdf')) self.add_static_path('/doc/static', DOC)
def __init__(self, *args, **kwds): self.startup_token = kwds.pop("startup_token", None) Flask.__init__(self, *args, **kwds) self.config["SESSION_COOKIE_HTTPONLY"] = False self.root_path = SAGENB_ROOT self.add_static_path("/css", os.path.join(DATA, "sage", "css")) self.add_static_path("/images", os.path.join(DATA, "sage", "images")) self.add_static_path("/javascript", DATA) self.add_static_path("/static", DATA) self.add_static_path("/java", DATA) self.add_static_path("/java/jmol", os.path.join(os.environ["SAGE_ROOT"], "local", "share", "jmol")) import mimetypes mimetypes.add_type("text/plain", ".jmol") ####### # Doc # ####### # These "should" be in doc.py DOC = os.path.join(SAGE_DOC, "output", "html", "en") self.add_static_path("/pdf", os.path.join(SAGE_DOC, "output", "pdf")) self.add_static_path("/doc/static", DOC)
def __init__(self, options, server): Flask.__init__(self, __name__) self._options = options self._server = server self.add_url_rule('/instance', 'status', self._status) self.add_url_rule('/instance', 'create-instance', self._create_instance, methods=['POST']) self.add_url_rule('/instance/<instance_id>', 'destroy-instance', self._destroy_instance, methods=['DELETE'])
def __init__(self, import_name, static_path=None, static_url_path=None, static_folder='html/static', template_folder='html/templates', instance_path=None, instance_relative_config=False, db_user=None, db_password=None, db_name=None): Flask.__init__( self, import_name=import_name, static_url_path= static_url_path, #didn't recognize static path so i took it out? static_folder=static_folder, template_folder=template_folder, instance_path=instance_path, instance_relative_config=instance_relative_config) #: DB connector pool. self.dbPool = SeaIceConnectorPool(MAX_CONNECTIONS, db_user, db_password, db_name) # Id pools. db_con = self.dbPool.getScoped() self.userIdPool = IdPool(db_con, "Users") #: Pool for user surrogate IDs. self.termIdPool = IdPool(db_con, "Terms") #: Pool for term surrogate IDs. self.commentIdPool = IdPool( db_con, "Comments") #: Pool for comment surrogate IDs. #: Live User data structures. This includes storage of notifications. self.SeaIceUsers = {} for row in db_con.getAllUsers(): self.SeaIceUsers[row['id']] = user.User( row['id'], row['first_name'].decode('utf-8')) # Load notifcations for (user_id, notif_class, T_notify, term_id, from_user_id, term_string, enotified) in db_con.getAllNotifications(): if notif_class == 'Base': notif = notify.BaseNotification(term_id, T_notify) elif notif_class == 'Comment': notif = notify.Comment(term_id, from_user_id, term_string, T_notify) elif notif_class == 'TermUpdate': notif = notify.TermUpdate(term_id, from_user_id, T_notify) elif notif_class == 'TermRemoved': notif = notify.TermRemoved(from_user_id, term_string, T_notify) self.SeaIceUsers[user_id].notify(notif)
def __init__(self, *args, **kwargs): gabby.Gabby.__init__(self, *args, **kwargs) Flask.__init__(self, ViewerAPI.__name__) self.info = None for route, fn in registered_routes.items(): partial_fn = partial(fn, self) partial_fn.__name__ = fn.__name__ self.route(route)(partial_fn)
def __init__(self, import_name, *args, **kwargs): if module_is_package(import_name): # Flask.__init__ sets static path based on sys.modules. # As such, import the package here to ensure it's in sys.modules. __import__(import_name) Flask.__init__(self, import_name, *args, **kwargs) self.set_default_config() self.writers = {} self.register_default_writers()
def __init__(self): Flask.__init__(self, __name__) self.config.from_object(__name__) path = os.path.dirname(os.path.realpath(__file__)) self.config.update(dict(VECTOR_FILE=path + '/GoogleNews-vectors.txt')) self.config.from_envvar('ROCANR_SETTINGS', silent=True) self.count = 0 self.model = KeyedVectors.load_word2vec_format( self.config['VECTOR_FILE'], binary=False)
def __init__(self, name): Flask.__init__(self, name) status_view = CephStatusView.as_view('status') self.add_url_rule('/', view_func=status_view) # add custom error handler for code in default_exceptions.iterkeys(): self.error_handler_spec[None][code] = self.make_json_error
def __init__(self, name): Flask.__init__(self, name) logging.config.dictConfig(config['logging']) self.request_class = CustomRequestClass self.endpoints = ApiEndpoints() self.__register_endpoints() self.__register_error_handler() self.__register_help_handler()
def __init__(self, name): template_folder = os.path.join(os.path.dirname(__file__), 'templates') Flask.__init__(self, name, template_folder=template_folder) status_view = CephStatusView.as_view('status') self.add_url_rule('/', view_func=status_view) # add custom error handler for code in default_exceptions.iterkeys(): self.error_handler_spec[None][code] = self.make_json_error
def __init__(self, name): Flask.__init__(self, name) dhc_view = StateView.as_view('status') self.add_url_rule('/', defaults={'env': None}, view_func=dhc_view) self.add_url_rule('/<env>', view_func=dhc_view) # add custom error handler for code in default_exceptions.iterkeys(): self.register_error_handler(code, self.make_json_error)
def __init__(self, wrapped_app, *args, **kwargs): Flask.__init__(self, *args, **kwargs) self.wrapped_app = wrapped_app self.config['SESSION_COOKIE_SECURE'] = False self.jinja_loader = ChoiceLoader([ self.jinja_loader, FileSystemLoader([ template_dir ]) ])
def __init__(self, env, debug=False, output_path=None, ui_lang='en', verbosity=0, build_flags=None): Flask.__init__(self, 'lektor.admin', static_url_path='/admin/static') self.lektor_info = LektorInfo(env, output_path, ui_lang, build_flags=build_flags, verbosity=verbosity) self.debug = debug self.config['PROPAGATE_EXCEPTIONS'] = True register_modules(self)
def __init__(self, *args, **kwargs): Flask.__init__(self, *args, **kwargs) self.config['br_time'] = { 'format': '%d/%m/%Y - %H:%M:%S', 'tz': pytz.timezone('America/Sao_Paulo') } self.config['SECRET_KEY'] = os.urandom(24).hex() self.config['TEMPLATES_AUTOR_RELOAD'] = True self.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0
def __init__(self): """ jinja_loader object (a FileSystemLoader pointing to the global templates folder) is being replaced with a ChoiceLoader object that will first search the normal FileSystemLoader and then check a PrefixLoader that we create """ Flask.__init__(self, __name__) self.jinja_loader = jinja2.ChoiceLoader( [self.jinja_loader, jinja2.PrefixLoader({}, delimiter=".")])
def __init__(self, name): Flask.__init__(self, name) logging.config.dictConfig(config['logging']) self.request_class = CustomRequestClass self.endpoints = ApiEndpoints() self._register_endpoints() self._register_error_handler() self._register_help_handler()
def __init__(self, *args, **kwargs): Flask.__init__(self, Server.__name__) self.host = os.environ.get("IXU_HOST", "0.0.0.0") self.port = int(os.environ.get("IXU_PORT", 8080)) self.project_id = os.environ.get("IXU_GITLAB_PROJECT_ID") for route, action in registered_routes.items(): fn, methods = action partial_fn = partial(fn, self) partial_fn.__name__ = fn.__name__ self.route(route, methods=methods)(partial_fn)
def __init__(self, module, config): Flask.__init__(self, module) # print(self.config) self.config = {**self.config, **config} # print(self.config) self.route("/", methods=["POST"])(self.execute) self.route("/interactive")(self.interactive) km, kc = jupyter_client.manager.start_new_kernel(kernel_name='python3') self.kc = kc self.socket_list = []
def __init__(self, name): template_folder = os.path.join(os.path.dirname(__file__), 'templates') static_folder = os.path.join(os.path.dirname(__file__), 'static') Flask.__init__(self, name, template_folder=template_folder, static_folder=static_folder) status_view = CephStatusView.as_view('status') self.add_url_rule('/', view_func=status_view) # add custom error handler for code in default_exceptions.iterkeys(): self.error_handler_spec[None][code] = self.make_json_error
def __init__(self, name, port, state, speed_limit): self.port = port self.state = state self.speed_limit = speed_limit self.vehicle_set = set() Flask.__init__(self, name) # register routes for route, fn in registered_routes.items(): partial_fn = partial(fn, self) partial_fn.__name__ = fn.__name__ self.route(route)(partial_fn)
def __init__(self, app_name='IoT REST API', cfg_from_object='web.config', api_uri='/iot/api/v0.1/'): Flask.__init__(self, import_name = app_name, static_path=None, static_url_path=None, static_folder=None, template_folder=None, instance_path=None, instance_relative_config=False) self.g = g self._BASE_API_URI = api_uri self.config.from_object(cfg_from_object) self.db = SQLAlchemy(self) self.api = Api(self) self.router = MethodType(self.route, self.api)
def __init__(self, name=None, *args, **kwargs): name = name or __name__ Flask.__init__(self, name, *args, **kwargs) ServiceManager.__init__(self) PluginManager.__init__(self) JinjaManagerMixin.__init__(self) self.default_view = ViewRegistry() self.js_api = {}
def __init__(self): """ jinja_loader object (a FileSystemLoader pointing to the global templates folder) is being replaced with a ChoiceLoader object that will first search the normal FileSystemLoader and then check a PrefixLoader that we create """ Flask.__init__(self, __name__, static_folder="static", template_folder="templates") self.jinja_loader = jinja2.ChoiceLoader([ self.jinja_loader, jinja2.PrefixLoader({}, delimiter=".") ])
def __init__(self, app_name, *args, **kwargs): """ :param: app_name - string, name of the application (can be anything) :keyword: local_config - dict, configuration that should be applied over the default config (that is loaded from config.py and local_config.py) """ proj_home = None if u'proj_home' in kwargs: proj_home = kwargs.pop(u'proj_home') self._config = load_config(extra_frames=1, proj_home=proj_home, app_name=app_name) if not proj_home: proj_home = self._config.get(u'PROJ_HOME', None) local_config = None if 'local_config' in kwargs: local_config = kwargs.pop(u'local_config') if local_config: self._config.update(local_config) # our config Flask.__init__(self, app_name, *args, **kwargs) self.config.update(self._config) self._logger = setup_logging( app_name, proj_home=proj_home, level=self._config.get(u'LOGGING_LEVEL', u'INFO'), attach_stdout=self._config.get(u'LOG_STDOUT', False)) self.db = None if self._config.get(u'SQLALCHEMY_DATABASE_URI', None): self.db = SQLAlchemy(self) # HTTP connection pool # - The maximum number of retries each connection should attempt: this # applies only to failed DNS lookups, socket connections and connection timeouts, # never to requests where data has made it to the server. By default, # requests does not retry failed connections. # http://docs.python-requests.org/en/latest/api/?highlight=max_retries#requests.adapters.HTTPAdapter self.client = requests.Session() http_adapter = requests.adapters.HTTPAdapter( pool_connections=self._config.get(u'REQUESTS_POOL_CONNECTIONS', 10), pool_maxsize=self._config.get(u'REQUESTS_POOL_MAXSIZE', 1000), max_retries=self._config.get(u'REQUESTS_POOL_RETRIES', 3), pool_block=False) self.client.mount(u'http://', http_adapter) self.before_request_funcs.setdefault(None, []).append(self._before_request) self.add_url_rule(u'/ready', u'ready', self.ready) self.add_url_rule(u'/alive', u'alive', self.alive)
def __init__(self, config: dict, path: str): sys.path.append(path) template_folder, static_folder, static_url = self.get_paths( config, path) Flask.__init__(self, '', static_url_path=static_url, static_folder=static_folder, template_folder=template_folder) self.url_map.converters['regex'] = RegexConverter WebsiteAppBase.__init__(self, config, path=path)
def __init__(self, *args, **kwargs): """Overriden Jinja constructor setting a custom jinja_environment""" self.jinja_environment = SandboxedBaseEnvironment self.session_interface = CachingSessionInterface(key_prefix="session") self.request_class = CTFdRequest # Store server start time self.start_time = datetime.datetime.utcnow() # Create generally unique run identifier self.run_id = sha256(str(self.start_time))[0:8] Flask.__init__(self, *args, **kwargs)
def __init__(self, import_name, path="./", url_prefix="/fs", debug=False, *args, **kwargs): LocalFSHandle.__init__(self, path) Flask.__init__(self, import_name=import_name, *args, **kwargs) self.url_prefix = url_prefix self.add_handlers() CORS(self, resources=r'/*')
def __init__(self, *args, **kwds): self.startup_token = kwds.pop('startup_token', None) Flask.__init__(self, *args, **kwds) self.session_interface = OldSecureCookieSessionInterface() self.config['SESSION_COOKIE_HTTPONLY'] = False self.root_path = SAGENB_ROOT self.add_static_path('/css', os.path.join(DATA, "sage", "css")) self.add_static_path('/images', os.path.join(DATA, "sage", "images")) self.add_static_path('/javascript', DATA) self.add_static_path('/static', DATA) self.add_static_path('/java', DATA) self.add_static_path('/java/jmol', os.path.join(os.environ["SAGE_SHARE"], "jmol")) self.add_static_path('/jsmol', os.path.join(os.environ["SAGE_SHARE"], "jsmol")) self.add_static_path( '/jsmol/js', os.path.join(os.environ["SAGE_SHARE"], "jsmol", "js")) self.add_static_path( '/j2s', os.path.join(os.environ["SAGE_SHARE"], "jsmol", "j2s")) self.add_static_path( '/jsmol/j2s', os.path.join(os.environ["SAGE_SHARE"], "jsmol", "j2s")) self.add_static_path( '/j2s/core', os.path.join(os.environ["SAGE_SHARE"], "jsmol", "j2s", "core")) self.add_static_path('/threejs', os.path.join(os.environ["SAGE_SHARE"], "threejs")) import mimetypes mimetypes.add_type('text/plain', '.jmol') ####### # Doc # ####### #These "should" be in doc.py DOC = os.path.join(SAGE_DOC, 'html', 'en') self.add_static_path('/pdf', os.path.join(SAGE_DOC, 'pdf')) self.add_static_path('/doc/static', DOC) # Template globals self.add_template_global(url_for) # Template filters self.add_template_filter(css_escape) self.add_template_filter(number_of_rows) self.add_template_filter(clean_name) self.add_template_filter(prettify_time_ago) self.add_template_filter(max) self.add_template_filter(lambda x: repr(unicode_str(x))[1:], name='repr_str') self.add_template_filter(dumps, 'tojson')
def __init__(self): # calls super constructor path = os.path.dirname(os.path.realpath(__file__)) Flask.__init__( self, "__main__", static_folder=path + "/gui/static", template_folder=path + "/gui/templates") # state variables initially empty self.camera = None self.car = None self.modes = [] self.active_mode = None
def __init__(self, *args, **kwargs): config = kwargs.pop('config', None) Flask.__init__(self, *args, **kwargs) self.config.from_object(DefaultConfig()) if config is not None: if isinstance(config, basestring): self.config.from_pyfile(config) else: self.config.from_object(config) self.configure_extensions()
def __init__(self, name): Flask.__init__(self, name) self.__add_apis = False self.__add_views = False self.__name = name self.url_map.converters["regex"] = _RegexConverter self.__init_config() self.__init_log() self.__init_sched() self.db = Database(self) self.cache = SimpleCache() self.__init_signals()
def __init__(self, name): Flask.__init__(self, name) self.response_class = MyResponse self._setup_hooks() # 注意这里的初始化顺序! self._init_stat() self._init_config() self._init_log() self._init_redis() self._init_db() logging.info('API开始服务请求')
def __init__(self, name: Optional[Any] = None, *args: Any, **kwargs: Any) -> None: name = name or __name__ Flask.__init__(self, name, *args, **kwargs) ServiceManager.__init__(self) PluginManager.__init__(self) JinjaManagerMixin.__init__(self) self.default_view = ViewRegistry() self.js_api = {}
def __init__(self, consumer_secret, endpoint, emitter, server): self.consumer_secret = consumer_secret self.emitter = emitter self.endpoint = endpoint # If a server is passed in, bind the event handler routes to it, # otherwise create a new Flask instance. if server: if isinstance(server, Flask): self.bind_route(server) else: raise TypeError("Server must be an instance of Flask") else: Flask.__init__(self, __name__) self.bind_route(self)
def __init__(self, *args, **kwargs): config = kwargs.pop('config', None) Flask.__init__(self, *args, **kwargs) self.config.from_object(DefaultConfig()) if config is None: self.config.from_object(config) with Connection(): self.queue = Queue() self.configure_extensions() self.register_blueprint(blueprint)
def __init__(self, config: Optional[Dict] = None): Flask.__init__(self, __name__) self.url_map.strict_slashes = False self.load_config() if config: self.config.update(config) register_error_handlers(self) self.register_blueprints() self.setup_depots() db.init_app(self) migrate.init_app(self, db)
def __init__(self, *args, **kwargs): config = kwargs.pop('config', None) Flask.__init__(self, *args, **kwargs) self.config.from_object(DefaultConfig()) if config is None: self.config.from_object(config) with Connection(): self.queue = Queue() self.configure_extensions() self.register_blueprint(blueprint) self.register_blueprint(blueprint_dashboard, url_prefix="/rq")
def __init__(self, signing_secret, endpoint, emitter, server): self.signing_secret = signing_secret self.emitter = emitter self.endpoint = endpoint self.package_info = self.get_package_info() # If a server is passed in, bind the event handler routes to it, # otherwise create a new Flask instance. if server: if isinstance(server, Flask) or isinstance(server, Blueprint): self.bind_route(server) else: raise TypeError("Server must be an instance of Flask or Blueprint") else: Flask.__init__(self, __name__) self.bind_route(self)
def __init__(self): """ jinja_loader object (a FileSystemLoader pointing to the global templates folder) is being replaced with a ChoiceLoader object that will first search the normal FileSystemLoader and then check a PrefixLoader that we create Since We can not create the elastic search instance globally for the flask application to consume. We add it as an attribute to the flask application. This will be available to the flask application instance and will use the host either from the environment variable or from a defined default. """ Flask.__init__(self, __name__, static_folder="static", template_folder="templates") self.jinja_loader = jinja2.ChoiceLoader([ self.jinja_loader, jinja2.PrefixLoader({}, delimiter=".") ]) # addition of the elasticsearch attribute to the flask application self.elasticsearch = Elasticsearch(os.environ.get("ELASTICSEARCH_URL", default="http://localhost:9200"))
def __init__(self, import_name, static_path=None, static_url_path=None, static_folder='static', template_folder='templates', instance_path=None, instance_relative_config=False): Flask.__init__(self, import_name, static_path, static_url_path, static_folder, template_folder, instance_path, instance_relative_config) print('init called') if os.path.exists(log) == True: with open(log, mode='rb') as f: SignatureDetector.df = pickle.load(f)
def __init__(self, verification_token, endpoint, emitter, server): self.verification_token = verification_token self.emitter = emitter self.endpoint = endpoint self.package_info = self.get_package_info() # If a server is passed in, bind the event handler routes to it, # otherwise create a new Flask instance. if server: if isinstance(server, Flask): self.bind_route(server) else: raise TypeError("Server must be an instance of Flask") else: Flask.__init__(self, __name__) self.bind_route(self)
def __init__(self, name): Flask.__init__(self, name) self.response_class = MyResponse self._register_error_handler(None, APIError, self.base_error_handler) self.before_request_funcs.setdefault(None, []).append(self.before_handler) self.teardown_request_funcs.setdefault(None, []).append(self.teardown_handler) # 注意这里的初始化顺序! self._init_config() self._init_log() self._init_redis() self._init_db() self._init_log_agent() self.logger.info('APP开始服务请求')
def __init__(self, import_name, static_url_path=None, static_folder='static', static_host=None, host_matching=False, subdomain_matching=False, template_folder='templates', instance_path=None, instance_relative_config=False, root_path=None): BaseFlask.__init__(self, import_name, static_url_path, static_folder, static_host, host_matching, subdomain_matching, template_folder, instance_path, instance_relative_config, root_path) self.__sendEmail = None return
def __init__(self, *args, **kwargs): self.endpoints = {} # This is the storage property for the endpoints self.__dict__.update({ method: self.__shorthand(methods=[method.upper()]) for method in ["get", "post", "put"]}) return Flask.__init__(self, *args, **kwargs)
def __init__(self, *args, **kwargs): self.endpoints = {} # This is the storage property for the endpoints if settings.DEBUG: if 'static_folder' not in kwargs and 'folder' in settings.STATIC: kwargs['static_folder'] = settings.STATIC['folder'] if 'static_url_path' not in kwargs and 'path' in settings.STATIC: kwargs['static_url_path'] = settings.STATIC['path'] return Flask.__init__(self, *args, **kwargs)
def __init__(self, implementation): Flask.__init__(self, __name__, static_url_path="/common_static") self.jinja_loader = jinja2.ChoiceLoader([ self.jinja_loader, jinja2.PrefixLoader({}, delimiter = ".") ]) sidebar_links = [] #Custom module importing #Import all controller modules in mod_* packages #if the define a "mod" attribute def import_dir(path, prefix): for _, package, _ in pkgutil.walk_packages([path]): if package[:4] == "mod_" or package == implementation: for _, module, _ in pkgutil.iter_modules([path + package]): if module == "controller": controller = importlib.import_module(prefix + "." + package + "." + module) if hasattr(controller, "mod"): self.register_blueprint(controller.mod) print "Registering:", prefix + "." + package + "." + module path = os.path.dirname(__file__) + "/" import_dir(path, "web_apps") import_dir(path + implementation + "/", "web_apps." + implementation) # HTTP error handling @self.errorhandler(404) def not_found(error): return render_template('404.html'), 404 # Make sure that the database is closed @self.teardown_appcontext def close_db(error): """Closes the database again at the end of the request.""" if hasattr(g, 'cursor'): g.cursor.close() if hasattr(g, 'database'): g.database.close() if hasattr(g, 'clientsDB'): g.clientsDB.close() """ End Init """
def __init__(self, *args, **kwds): self.startup_token = kwds.pop('startup_token', None) Flask.__init__(self, *args, **kwds) self.session_interface = OldSecureCookieSessionInterface() self.config['SESSION_COOKIE_HTTPONLY'] = False self.root_path = SAGENB_ROOT self.add_static_path('/css', os.path.join(DATA, "sage", "css")) self.add_static_path('/images', os.path.join(DATA, "sage", "images")) self.add_static_path('/javascript', DATA) self.add_static_path('/static', DATA) self.add_static_path('/java', DATA) self.add_static_path('/java/jmol', os.path.join(os.environ["SAGE_SHARE"],"jmol")) self.add_static_path('/jsmol', os.path.join(os.environ["SAGE_SHARE"],"jsmol")) self.add_static_path('/jsmol/js', os.path.join(os.environ["SAGE_SHARE"],"jsmol","js")) self.add_static_path('/j2s', os.path.join(os.environ["SAGE_SHARE"],"jsmol","j2s")) self.add_static_path('/jsmol/j2s', os.path.join(os.environ["SAGE_SHARE"],"jsmol","j2s")) self.add_static_path('/j2s/core', os.path.join(os.environ["SAGE_SHARE"],"jsmol","j2s","core")) self.add_static_path('/threejs', os.path.join(os.environ["SAGE_SHARE"],"threejs")) import mimetypes mimetypes.add_type('text/plain','.jmol') ####### # Doc # ####### #These "should" be in doc.py DOC = os.path.join(SAGE_DOC, 'html', 'en') self.add_static_path('/pdf', os.path.join(SAGE_DOC, 'pdf')) self.add_static_path('/doc/static', DOC) # Template globals self.add_template_global(url_for) # Template filters self.add_template_filter(css_escape) self.add_template_filter(number_of_rows) self.add_template_filter(clean_name) self.add_template_filter(prettify_time_ago) self.add_template_filter(max) self.add_template_filter(lambda x: repr(unicode_str(x))[1:], name='repr_str') self.add_template_filter(dumps, 'tojson')
def __init__(self, import_name, static_path=None, static_url_path=None, static_folder='html/static', template_folder='html/templates', instance_path=None, instance_relative_config=False, db_user=None, db_password=None, db_name=None): Flask.__init__(self, import_name, static_path, static_url_path, static_folder, template_folder, instance_path, instance_relative_config) #: DB connector pool. self.dbPool = SeaIceConnectorPool(MAX_CONNECTIONS, db_user, db_password, db_name) # Id pools. db_con = self.dbPool.getScoped() self.userIdPool = IdPool(db_con, "Users") #: Pool for user surrogate IDs. self.termIdPool = IdPool(db_con, "Terms") #: Pool for term surrogate IDs. self.commentIdPool = IdPool(db_con, "Comments") #: Pool for comment surrogate IDs. #: Live User data structures. This includes storage of notifications. self.SeaIceUsers = {} for row in db_con.getAllUsers(): self.SeaIceUsers[row['id']] = user.User(row['id'], row['first_name'].decode('utf-8')) # Load notifcations for (user_id, notif_class, T_notify, term_id, from_user_id, term_string, enotified) in db_con.getAllNotifications(): if notif_class == 'Base': notif = notify.BaseNotification(term_id, T_notify) elif notif_class == 'Comment': notif = notify.Comment(term_id, from_user_id, term_string, T_notify) elif notif_class == 'TermUpdate': notif = notify.TermUpdate(term_id, from_user_id, T_notify) elif notif_class == 'TermRemoved': notif = notify.TermRemoved(from_user_id, term_string, T_notify) self.SeaIceUsers[user_id].notify(notif)
def __init__(self, import_name, db_controller = None, bus = None): #super(SlaPrinterApp, self).__init__(import_name, template_folder=TEMPLATE_DIR, static_url_path=STATIC_DIR) Flask.__init__(self,import_name, static_folder=STATIC_DIR, template_folder=TEMPLATE_DIR) Observable.__init__(self, bus) Observer.__init__(self, bus) Process.__init__(self) self.exit = Event() self.endpoint_prefix = None for name in dir(self): if hasattr(getattr(self, name), ("_routing_data")): fn = getattr(self, name) rds = fn._routing_data for rd in rds: self.route(*rd.args, **rd.kwargs)(fn) self.register_error_handler(404, self.page_not_found) self.db_controller = db_controller print("Flask Server initializing")
def __init__(self, *args, **kwargs): self.endpoints = {} # This is the storage property for the endpoints if settings.DEBUG: if 'static_folder' not in kwargs and 'folder' in settings.STATIC: kwargs['static_folder'] = settings.STATIC['folder'] if 'static_url_path' not in kwargs and 'path' in settings.STATIC: kwargs['static_url_path'] = settings.STATIC['path'] self.__dict__.update({ method: self.__shorthand({'methods': [method.upper()]}) for method in ["get", "post", "put"]}) return Flask.__init__(self, *args, **kwargs)
def __init__(self, *args, **kwds): self.startup_token = kwds.pop('startup_token', None) Flask.__init__(self, *args, **kwds) self.root_path = SAGENB_ROOT self.add_static_path('/css', os.path.join(DATA, "sage", "css")) self.add_static_path('/images', os.path.join(DATA, "sage", "images")) self.add_static_path('/javascript', DATA) self.add_static_path('/static', DATA) self.add_static_path('/java', DATA) import mimetypes mimetypes.add_type('text/plain','.jmol') ####### # Doc # ####### #These "should" be in doc.py DOC = os.path.join(SAGE_DOC, 'output', 'html', 'en') self.add_static_path('/pdf', os.path.join(SAGE_DOC, 'output', 'pdf')) self.add_static_path('/doc/static', DOC)
def __init__(self, config): Flask.__init__(self, __name__) # TODO: deal with envvar and pyfile self.config.from_object(config) # Initialise helpers and services db.init_app(self) mail.init_app(self) # Babel (for i18n) babel.init_app(self) babel.localeselector(get_locale) # celery async service celery.config_from_object(config) # Initialise filters init_filters(self) # init_auth(self) self.register_services()
def __init__(self, config): Flask.__init__(self, __name__) # TODO: deal with envvar and pyfile self.config.from_object(config) # Initialise helpers and services db.init_app(self) mail.init_app(self) # Babel babel.init_app(self) babel.localeselector(get_locale) # DEBUG self.jinja_env.add_extension('jinja2.ext.i18n') self.jinja_env.install_gettext_callables( lambda x: x, lambda s, p, n: p, newstyle=True ) # Assets (bundles are defined in the templates) assets = Environment(self) # Initialise filters init_filters(self) init_auth(self) from .apps.crm.frontend import CRM crm = CRM(self) self.register_blueprints() # Must come after all entity classes have been declared. self.register_services()