class BaseDatabase: """The base database class to be used with Peewee. """ def __init__(self): self.path = None self.db = SqliteDatabase(None) def initialize(self, path): self.path = path self.db.init(path) self._post_initialization() def _post_initialization(self): from papergit.models import PaperDoc, PaperFolder, Sync try: self.db.create_tables([PaperDoc, PaperFolder, Sync]) except OperationalError as e: if "already exists" in str(e): return raise
def test_deferred_database(self): deferred_db = SqliteDatabase(None) self.assertTrue(deferred_db.deferred) class DeferredModel(Model): class Meta: database = deferred_db self.assertRaises(Exception, deferred_db.connect) sq = DeferredModel.select() self.assertRaises(Exception, sq.execute) deferred_db.init(':memory:') self.assertFalse(deferred_db.deferred) # connecting works conn = deferred_db.connect() DeferredModel.create_table() sq = DeferredModel.select() self.assertEqual(list(sq), []) deferred_db.init(None) self.assertTrue(deferred_db.deferred)
class BaseDatabase: """The base database class to be used with Peewee. """ def __init__(self, url=None): self.url = url self.db = SqliteDatabase(None) def initialize(self, url=None): if url is not None: self.url = url else: raise ValueError self.db.init(url) self._post_initialization() return self.db def _post_initialization(self): from paper_to_git.models import PaperDoc, PaperFolder, Sync self.db.connect() try: self.db.create_tables([PaperDoc, PaperFolder, Sync]) except OperationalError: # The database already exists. pass
class Workspace: """Workspace handling class """ WORKSPACES = Path( os.environ.get("SPACE_WORKSPACES_FOLDER", Path.home() / ".space/")) HOOKS = ("init", "status", "full-init") DEFAULT = "main" def __new__(cls, *args, **kwargs): # Singleton if not hasattr(cls, "_instance"): cls._instance = super().__new__(cls, *args, **kwargs) return cls._instance def __init__(self, name=None): self.db = SqliteDatabase(None) self.db.ws = self self.config = SpaceConfig(self) self.name = name if name is not None else self.DEFAULT def __repr__(self): return "<Workspace '{}'>".format(self.name) @classmethod def list(cls): """List available workspaces """ for _ws in cls.WORKSPACES.iterdir(): if _ws.is_dir(): if _ws.name == "_backup": continue yield _ws def _db_init(self): filepath = self.folder / "space.db" self.db.init(str(filepath)) log.debug("{} database initialized".format(filepath.name)) def load(self): """Load the workspace """ self.config.load() log.debug("{} loaded".format(self.config.filepath.name)) self._db_init() log.debug("workspace '{}' loaded".format(self.name)) def delete(self): if not self.folder.exists(): raise FileNotFoundError(self.folder) shutil.rmtree(str(self.folder)) log.info("Workspace '{}' deleted".format(self.name)) @property def folder(self): """Path to the folder of this workspace, as a pathlib.Path object """ return self.WORKSPACES / self.name def exists(self): return self.folder.exists() def init(self, full=False): """Initilize the workspace """ print("Initializing workspace '{}'".format(self.name)) if not self.exists(): self.folder.mkdir(parents=True) # Due to the way peewee works, we have to initialize the database # even before the creation of any file self._db_init() if full: self._trigger("full-init") else: self._trigger("init") log.debug("{} workspace initialized".format(self.name)) def status(self): log.info("Workspace '{}'".format(self.name)) log.info("folder {}".format(self.folder)) log.info("db {}".format(self.db.database)) log.info("config {}".format(self.config.filepath.name)) self._trigger("status") def _trigger(self, cmd): if cmd not in self.HOOKS: raise ValueError("Unknown workspace command '{}'".format(cmd)) # Each command is responsible of its own initialization, logging and error handling for entry in sorted(iter_entry_points("space.wshook"), key=lambda x: x.name): entry.load()(cmd) def backup(self, filepath=None): """Backup the current workspace into a tar.gz file """ if filepath is None: name = "{}-{:%Y%m%d_%H%M%S}.tar.gz".format(self.name, datetime.utcnow()) filepath = self.WORKSPACES / "_backup" / name if not filepath.parent.exists(): filepath.parent.mkdir(parents=True) def _filter(tarinfo): """Filtering function """ if "tmp" in tarinfo.name or "jpl" in tarinfo.name: return None else: return tarinfo log.info("Creating backup for workspace '{}'".format(self.name)) with tarfile.open(filepath, "w:gz") as tar: tar.add(self.folder, arcname=self.name, filter=_filter) log.info("Backup created at {}".format(filepath))
from flask import Flask from flask_peewee.db import Database from peewee import SqliteDatabase PEEWEE_DB = SqliteDatabase(None) app = Flask(__name__) app.config.from_object('gistsurfr.settings') PEEWEE_DB.init( app.config['DATABASE']['name'], ) db = Database(app)
class Pomito(object): """Controls the application lifetime. Responsibilities: - Read and initialize the configuration - Choose the run mode - Handover execution to UI plugin """ def __init__(self, config=None, database=None, message_dispatcher=None): """Create a Pomito object. Arguments: config Configuration Path to the configuration file database peewee.SqliteDatabase database to use for tasks etc. message_dispatcher MessageDispatcher message dispatcher instance """ from pomito import pomodoro self._config = config self._database = database self._message_dispatcher = message_dispatcher self._threads = {} self._hooks = [] if self._message_dispatcher is None: self._message_dispatcher = MessageDispatcher() if self._config is None: self._config_file = os.path.join(CONFIG_DIR, "config.ini") self._config = Configuration(self._config_file) self._config.load() # Pomodoro service instance. Order of initializations are important self.pomodoro_service = pomodoro.Pomodoro(self) # Default plugins pomito.plugins.initialize(self.pomodoro_service) self.ui_plugin = pomito.plugins.get_plugin(self._config.ui_plugin) self.task_plugin = pomito.plugins.get_plugin(self._config.task_plugin) # Add the plugins to threads list self._threads['task_plugin'] = threading.Thread(target=self.task_plugin) # Default hooks from pomito.hooks import activity self._hooks.append(activity.ActivityHook(self.pomodoro_service)) return def initialize(self): """Initialize configuration, database and starts worker threads.""" os.makedirs(DATA_DIR, exist_ok=True) database_path = os.path.join(DATA_DIR, "pomito.db") if self._database is None: self._database = SqliteDatabase(None) self._database.init(database_path) self._database.connect() # Initialize the plugins self.ui_plugin.initialize() self.task_plugin.initialize() # Initialize the hooks for hook in self._hooks: hook.initialize() return def run(self): """Start the application.""" if not self._validate_state(): logger.critical("Pomito.Run: Invalid state. Exiting.") return self.initialize() self._message_dispatcher.start() self.ui_plugin.run() self.exit() def exit(self): """Clean up and save any configuration data. Prepare for exiting the application.""" if self._message_dispatcher.is_alive(): self._message_dispatcher.stop() self._message_dispatcher.join() for hook in self._hooks: hook.close() if self._database is not None: self._database.close() def get_db(self): """Get the database object. Returns: database peewee.SqliteDatabase object """ return self._database def get_configuration(self): return self._config def queue_signal(self, message): self._message_dispatcher.queue_message(message) def _validate_state(self): """Validates configuration, plugins.""" import pomito.plugins _retval = True if not issubclass(type(self.ui_plugin), pomito.plugins.ui.UIPlugin): logger.error("Invalid UIPlugin object = {0}".format(self.ui_plugin)) _retval = False if not issubclass(type(self.task_plugin), pomito.plugins.task.TaskPlugin): logger.error("Invalid TaskPlugin object = {0}".format(self.task_plugin)) _retval = False return _retval
class Pomito(object): """Controls the application lifetime. Responsibilities: - Read and initialize the configuration - Choose the run mode - Handover execution to UI plugin """ def __init__(self, config=None, database=None, message_dispatcher=None): """Create a Pomito object. Arguments: config Configuration Path to the configuration file database peewee.SqliteDatabase database to use for tasks etc. message_dispatcher MessageDispatcher message dispatcher instance """ from pomito import pomodoro self._config = config self._database = database self._message_dispatcher = message_dispatcher self._threads = {} self._hooks = [] if self._message_dispatcher is None: self._message_dispatcher = MessageDispatcher() if self._config is None: self._config_file = os.path.join(CONFIG_DIR, "config.ini") self._config = Configuration(self._config_file) self._config.load() # Pomodoro service instance. Order of initializations are important self.pomodoro_service = pomodoro.Pomodoro(self) # Default plugins pomito.plugins.initialize(self.pomodoro_service) self.ui_plugin = pomito.plugins.get_plugin(self._config.ui_plugin) self.task_plugin = pomito.plugins.get_plugin(self._config.task_plugin) # Add the plugins to threads list self._threads['task_plugin'] = threading.Thread( target=self.task_plugin) # Default hooks from pomito.hooks import activity self._hooks.append(activity.ActivityHook(self.pomodoro_service)) return def initialize(self): """Initialize configuration, database and starts worker threads.""" os.makedirs(DATA_DIR, exist_ok=True) database_path = os.path.join(DATA_DIR, "pomito.db") if self._database is None: self._database = SqliteDatabase(None) self._database.init(database_path) self._database.connect() # Initialize the plugins self.ui_plugin.initialize() self.task_plugin.initialize() # Initialize the hooks for hook in self._hooks: hook.initialize() return def run(self): """Start the application.""" if not self._validate_state(): logger.critical("Pomito.Run: Invalid state. Exiting.") return self.initialize() self._message_dispatcher.start() self.ui_plugin.run() self.exit() def exit(self): """Clean up and save any configuration data. Prepare for exiting the application.""" if self._message_dispatcher.is_alive(): self._message_dispatcher.stop() self._message_dispatcher.join() for hook in self._hooks: hook.close() if self._database is not None: self._database.close() def get_db(self): """Get the database object. Returns: database peewee.SqliteDatabase object """ return self._database def get_configuration(self): return self._config def queue_signal(self, message): self._message_dispatcher.queue_message(message) def _validate_state(self): """Validates configuration, plugins.""" import pomito.plugins _retval = True if not issubclass(type(self.ui_plugin), pomito.plugins.ui.UIPlugin): logger.error("Invalid UIPlugin object = {0}".format( self.ui_plugin)) _retval = False if not issubclass(type(self.task_plugin), pomito.plugins.task.TaskPlugin): logger.error("Invalid TaskPlugin object = {0}".format( self.task_plugin)) _retval = False return _retval