当前位置: 首页>>代码示例>>Python>>正文


Python db.DB类代码示例

本文整理汇总了Python中lib.db.DB的典型用法代码示例。如果您正苦于以下问题:Python DB类的具体用法?Python DB怎么用?Python DB使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了DB类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: __init__

    def __init__(self, parent):
        '''
        Constructor
        '''
        log.info("***StorePanel.init")
        gui.StoragePanel.__init__(self, parent)

        self.db = DB()
        self.config = Config.get_config()
        self.state = ViewState
        self.load_static_data()
        self.update_store_list()
        self.clear()
        if self.lstItems.GetCount() > 0:
            self.lstItems.SetSelection(0)
            self.onItemSelected(None)

        self.onAutoManage(None)
        self.image = wx.Bitmap(os.path.join(const.PixmapDir, "storage.png"))
        self.title = _("Storage")

        self.ftp_hidden = True
        self.db_hidden = True

        log.trace("Done StorePanel.init")
开发者ID:,项目名称:,代码行数:25,代码来源:

示例2: __init__

    def __init__(self, parent):
        '''
        Constructor
        '''
        log.info("***BackupPanel.init")
        gui.BackupPanel.__init__(self, parent)
        self.btnAddFolder.SetBitmapLabel(wx.Bitmap(os.path.join(const.PixmapDir, "add.png")))
        
        self.db = DB()
        self.config = Config.get_config()

        self.state = ViewState
        self.update_data(False)
        self.nbBackup.SetSelection(0)
        self.clear()
        self.nbBackup.Layout()
        self.Fit()
        self.radSchedDailyWeekly.SetValue(True)

        if self.lstItems.GetCount() > 0:
            self.lstItems.SetSelection(0)
            self.onItemSelected(None)
#        self.onNotifyEmail(None)
        self.image = wx.Bitmap(os.path.join(const.PixmapDir, "backup.png"))
        self.title = _("Backups")

        self.onBackupSchedule(None)
        log.trace("Done BackupPanel.init")
开发者ID:tussock,项目名称:Vault,代码行数:28,代码来源:backuppanel.py

示例3: __init__

    def __init__(self, test_folder, options):

        self.test_folder = os.path.join(test_folder, "tester")
        self.options = options
        self.config = Config.get_config()

        self.store_folder = os.path.join(self.test_folder, "stores")
        self.files_folder = os.path.join(self.test_folder, "files")
        self.restore_folder = os.path.join(self.test_folder, "restore")

        self.db = DB()

        self.max_fs_id = self.db.query("select max(fs_id) from fs", ())[0][0]
        if self.max_fs_id is None:
            self.max_fs_id = 0
        self.max_version_id = self.db.query("select max(version_id) from versions", ())[0][0]
        if self.max_version_id is None:
            self.max_version_id = 0
        self.max_run_id = self.db.query("select max(run_id) from runs", ())[0][0]
        if self.max_run_id is None:
            self.max_run_id = 0
        self.max_message_id = self.db.query("select max(message_id) from messages", ())[0][0]
        if self.max_message_id is None:
            self.max_message_id = 0
        log.debug("MAX IDs", self.max_fs_id, self.max_version_id, self.max_run_id, self.max_message_id)

        self.teststring1 = os.urandom(204800)
        self.teststring2 = os.urandom(204800)
开发者ID:tussock,项目名称:Vault,代码行数:28,代码来源:tester.py

示例4: __init__

 def __init__(self,app,onlyDBAccess=False):
     '''main window init'''
     QtGui.QMainWindow.__init__(self)
     self.ui = Ui_MainWindow()
     self.ui.setupUi(self)
     self.db = DB(self)
     self.settings=Settings(self)
     self.onlyDBAccess=onlyDBAccess
     if onlyDBAccess:
         return 
     #GUI setting
     guiSettings(self)
     connectSignals(self)
     changeStyle(self)
     
     self.taskOpened = False
     self.app = app
     loadContexts(self)
     self.currentContext = self.settings.getInitContext()
     selectCurrentContext(self)
     self.loadTasksList(init=True)  
     self.tray=Trayicon(self)
     self.timer=TaskReminder(self)
     self.shortcuts=ShortcutsHandler(self,self.settings['keyMainWindowToggle'])
     finalizeInit(self)
     self.translate()
     self.adjustHeight(init=True)
开发者ID:middleofdreams,项目名称:workload,代码行数:27,代码来源:main.py

示例5: __init__

    def __init__(self, parent):
        '''
        Constructor
        '''
        log.info("***ConfigPanel.init")

        gui.ConfigPanel.__init__(self, parent)
        self.config = Config.get_config()
        self.db = DB()        

        self.state = ViewState
        self.update_filetype_list()
        self.clear_filetype()
        self.image = wx.Bitmap(os.path.join(const.PixmapDir, "configure.png"))
        self.title = _("Configuration")
        if self.lstFileTypes.GetCount() > 0:
            self.lstFileTypes.SetSelection(0)
            self.onFileType(None)
        self.show_mail()
        self.txtMailServer.SetFocus()
        self.nb_config.SetSelection(0)

        self.show_security()
        self.pwd_hidden = True
        self.mail_hidden = True

        log.trace("Done ConfigPanel.init")
开发者ID:tussock,项目名称:Vault,代码行数:27,代码来源:configpanel.py

示例6: __init__

 def __init__(self):
     # open syslog and notice startup
     syslog.openlog('captiveportal', logoption=syslog.LOG_DAEMON)
     syslog.syslog(syslog.LOG_NOTICE, 'starting captiveportal background process')
     # handles to ipfw, arp the config and the internal administration
     self.ipfw = IPFW()
     self.arp = ARP()
     self.cnf = Config()
     self.db = DB()
     self._conf_zone_info = self.cnf.get_zones()
开发者ID:gdsellerPd,项目名称:core,代码行数:10,代码来源:cp-background-process.py

示例7: __init__

    def __init__(self, backup_name, run_date):
        '''
        Verify a run to ensure it is valid
        
        '''
        self.config = Config.get_config()
        self.backup = self.config.backups[backup_name]
        self.store = self.config.storage[self.backup.store].copy()

        self.db = DB()

        #    Find the run
        runs = self.db.runs(self.backup.name, run_date)
        if len(runs) == 0:
            raise Exception(_("Verify failed: Backup run does not exist"))
        self.vrun = runs[0]
开发者ID:tussock,项目名称:Vault,代码行数:16,代码来源:verify.py

示例8: __init__

    def __init__(self, name, type, options):
        '''
        Prepare to run a backup event
        
        @param name: name of the backup
        @param type: type (Full/Incr)
        @param type: dry_run
        
        If dry_run is True, then we will print the files we *would have* backed
        up to stdout.
        
        '''
        self.type = type
        self.dry_run = options.dry_run
        self.options = options
        self.config = Config.get_config()

        try:
            self.backup = self.config.backups[name]
        except:
            raise Exception(_("Backup is missing or corrupt. Please reconfigure backup."))

        try:
            #    Get a fresh store (a copy of the config version
            self.store = self.config.storage[self.backup.store].copy()
        except:
            raise Exception(_("Storage definition is missing. Please reconfigure backup."))

        self.db = DB()
        self.start_time = None
        self.nfiles = None
        self.nfolders = None
        self.bytes = None
        self.run_id = None
        self.backup_folder = None

        #    Make sure there are no other backups running of this name
        self.lock = locking.InterProcessLock(name="Vault-%s" % self.backup.name)

        #    Build a quick file exclusion list, to speed up exclusion checking
        self.excl_ext = self.build_excl_exts()
        log.debug("Exclusion List:", ",".join(self.excl_ext))
开发者ID:tussock,项目名称:Vault,代码行数:42,代码来源:run.py

示例9: setUp

    def setUp(self):
        self.config = Config.get_config()

        self.db = DB()
        self.db.check_upgrade()
        self.mark_db_ids()

        self.test_folder = tempfile.mkdtemp()
        self.files_folder = os.path.join(self.test_folder, "files")
        self.store_folder = os.path.join(self.test_folder, "store")
        self.restore_folder = os.path.join(self.test_folder, "restore")
        utils.makedirs(self.files_folder)
        utils.makedirs(self.store_folder)
        utils.makedirs(self.restore_folder)

        utils.build_file_structure(self.files_folder, 50 * const.Kilobyte, 500 * const.Kilobyte)

        #    Build a store object (dont save config)
        #    Note the careful size selection - we want backups to overflow the FolderStore.
        self.store = FolderStore("teststore", "2MB", True, self.store_folder)
        self.config.storage[self.store.name] = self.store

        #    Build the backup object (dont save config)
        self.backup = Backup("testbackup")
        self.backup.include_folders = [self.files_folder]
        self.backup.store = self.store.name
        self.backup.notify_msg = False
        self.include_packages = True
        self.config.backups[self.backup.name] = self.backup

        #    build an options object for use with the backup
        self.options = BlankClass()
        self.options.dry_run = False
        self.options.message = False
        self.options.email = False
        self.options.shutdown = False
        self.options.norecurse = False

        self.old_pass = self.config.data_passphrase
        self.config.data_passphrase = "banana"
开发者ID:tussock,项目名称:Vault,代码行数:40,代码来源:test_verify.py

示例10: Tester

class Tester():
    def __init__(self, test_folder, options):

        self.test_folder = os.path.join(test_folder, "tester")
        self.options = options
        self.config = Config.get_config()

        self.store_folder = os.path.join(self.test_folder, "stores")
        self.files_folder = os.path.join(self.test_folder, "files")
        self.restore_folder = os.path.join(self.test_folder, "restore")

        self.db = DB()

        self.max_fs_id = self.db.query("select max(fs_id) from fs", ())[0][0]
        if self.max_fs_id is None:
            self.max_fs_id = 0
        self.max_version_id = self.db.query("select max(version_id) from versions", ())[0][0]
        if self.max_version_id is None:
            self.max_version_id = 0
        self.max_run_id = self.db.query("select max(run_id) from runs", ())[0][0]
        if self.max_run_id is None:
            self.max_run_id = 0
        self.max_message_id = self.db.query("select max(message_id) from messages", ())[0][0]
        if self.max_message_id is None:
            self.max_message_id = 0
        log.debug("MAX IDs", self.max_fs_id, self.max_version_id, self.max_run_id, self.max_message_id)

        self.teststring1 = os.urandom(204800)
        self.teststring2 = os.urandom(204800)


    def run(self):
        try:
            self.simpleCycleTest()
            self.restoreTest()
        except:
            pass
            
        if self.options.message:
            try:
                from lib.dlg import Notify
                Notify(const.AppTitle, "Test run is complete")
            except:
                log.debug("Unable to notify. No-one logged in?")
        if self.options.email:
            self.send_email(True)
        if self.options.shutdown:
            os.system("shutdown -P +2")
        
        
    def simpleCycleTest(self):
        try:
            #   build the test files/folders
            self.make_folders()
            #    fill the files folder with the initial set of files
            self.fill_files()


            #    Build a backup and store
            self.build_config()

#            self.run_test()

            for i in xrange(int(self.options.cycles)):
                log.info("Cycle", i)
                #    Run a full and one incremental 
                self.run_cycle_test()

        except Exception as e:
            log.error("Test run failed: %s" % str(e))
        finally:
            self.cleanup()

        log.info("********Success")

    def restoreTest(self):
        try:
            #   build the test files/folders
            self.make_folders()
            #    fill the files folder with the initial set of files
            self.fill_files()
        except:
            pass

#    def build_config(self):
#        log.trace("build_config")
#        try:
#            if self.options.store:
#                store = self.config.storage[self.options.store]
#            else:
#                #    Make the store about 3x the options size
#                s, dummy, dummy = utils.from_readable_form(self.options.size)
#                store_size = utils.readable_form(s * 3)
#                store = FolderStore("teststore1", store_size, True, os.path.join(self.store_folder, "teststore1"))
#                self.config.storage[store.name] = store
#    
#            backup = Backup("testbackup1")
#            backup.include_folders = [self.files_folder]
#            backup.store = store.name
#            backup.notify_msg = False
#.........这里部分代码省略.........
开发者ID:tussock,项目名称:Vault,代码行数:101,代码来源:tester.py

示例11: len

# parse input parameters
parameters = {"sessionid": None, "zoneid": None, "output_type": "plain"}
current_param = None
for param in sys.argv[1:]:
    if len(param) > 1 and param[0] == "/":
        current_param = param[1:].lower()
    elif current_param is not None:
        if current_param in parameters:
            parameters[current_param] = param.strip()
        current_param = None

# disconnect client
response = {"terminateCause": "UNKNOWN"}
if parameters["sessionid"] is not None and parameters["zoneid"] is not None:
    cp_db = DB()
    # remove client
    client_session_info = cp_db.del_client(parameters["zoneid"], parameters["sessionid"])
    if client_session_info is not None:
        cpIPFW = IPFW()
        cpIPFW.delete_from_table(parameters["zoneid"], client_session_info["ip_address"])
        client_session_info["terminateCause"] = "User-Request"
        response = client_session_info

# output result as plain text or json
if parameters["output_type"] != "json":
    for item in response:
        print "%20s %s" % (item, response[item])
else:
    print (ujson.dumps(response))
开发者ID:karawan,项目名称:core,代码行数:29,代码来源:disconnect.py

示例12: Geocoder

import sys
import logging
import time

from lib.geocoder import Geocoder
from lib.db import DB


logging.basicConfig(level=logging.DEBUG,
    format='%(asctime)s %(levelname)s %(message)s',
    filename='./log/location_geocoder.log',
    filemode='w')

conf_file = 'data/geocoder.conf'
geocoder = Geocoder(logging, conf_file)
db = DB(logging)

while True:
    users = db.get_geocoding_target_users(100)
    if len(users) == 0:
        logging.info("All users in DB are geocoded.")
        time.sleep(10*60)
        continue

    for user in users:
        if user['location_property'] == '':
            db.update_user_by_geocoded_info(user['id'], -1)
            logging.info("Cannot geocoded %s", user['id'])
            time.sleep(10)
            continue
        locations = geocoder.get(user['location_property'])
开发者ID:yamaguchiyuto,项目名称:bagel,代码行数:31,代码来源:location_geocoder.py

示例13: main

def main():

    try :

        #
        # CONFIGURACIÓN
        #

        # Gestor de base de datos
        db = DB()

        # Carga los valores de configuración
        config = Config(db)

        # Listas de probabilidades de aparación
        probabilidad_enemigos = db.get_probabilidad('enemigos')
        probabilidad_gemas = db.get_probabilidad('gemas')

        # Instancia un reloj para controlar el tiempo
        reloj = pygame.time.Clock()

        #
        # VENTANA
        #

        # Crea la ventana
        ventana = pygame.display.set_mode((config.ventana_ancho, config.ventana_alto))

        # Título de la ventana
        pygame.display.set_caption('Gemas')

        # Carga el fondo (convirtiéndolo al formato usado en SDL para mejorar la eficiencia)
        fondo = pygame.image.load(os.path.join(config.dir_img, 'fondo.jpg')).convert()

        # Inicia partidas hasta que el usuario decide terminar la ejecución del programa
        salir = False
        while not salir:

            #
            # SPRITES
            #

            # Diccionario de sprites activos en cada momento
            sprites_activos = {}

            # Instancia al jugador y lo añade a la lista de sprites activos
            jugador = Jugador(config)
            sprites_activos['jugador'] = jugador

            # Instancia dos enemigos y los añade a la lista de sprites activos
            sprites_activos['enemigo'] = [Enemigo(config, 0), Enemigo(config, 1)]

            # Indica el momento en el que se generó el último enemigo
            ultimo_enemigo_respawn = pygame.time.get_ticks()

            # Instancia las gemas y las añade a la lista de sprites activos
            #
            # Hay varios tipos de gemas, cada una con una probabilidad distinta de ser
            # generada. La generación de las gemas es aleatoria pero teniendo en cuenta
            # dicha probabilidad
            sprites_activos['gema'] = []
            for i in range(1, config.gema_max_activas + 1):
                tipo_gema = get_tipo(probabilidad_gemas)
                gema = Gema(config, tipo_gema, sprites_activos)
                sprites_activos['gema'].append(gema)

            # Indica el momento en que ha de generarse una nueva gema (0 = no se genera ninguna)
            proximo_respawn_gema = 0

            # Marcador
            marcador = Marcador(config)
            sprites_activos['marcador'] = marcador

            # Puntuación máxima
            record = Record(config, db)
            sprites_activos['record'] = record
            
            # Fin de partida
            gameover = GameOver(config)


            #
            # BUCLE DE EVENTOS
            #

            # El programa permanece funcionando hasta que se cierra la ventana
            # Cada iteración del bucle es un frame
            fin_partida = False
            while not fin_partida:

                # Averigua el tiempo (en milisegundos) transcurrido por cada frame
                # Además, al usar FRAMERATE en la llamada, se fija el número de frames por segundo
                # independientemente del hardware de la máquina
                tiempo = reloj.tick(config.framerate)

                # Obtiene y recorre la lista de eventos que están teniendo lugar
                for evento in pygame.event.get():

                    # Si encuentra el evento QUIT termina la ejecución
                    if evento.type == QUIT:
#.........这里部分代码省略.........
开发者ID:camador,项目名称:curso_python,代码行数:101,代码来源:juego.py

示例14: Verify

class Verify():
    def __init__(self, backup_name, run_date):
        '''
        Verify a run to ensure it is valid
        
        '''
        self.config = Config.get_config()
        self.backup = self.config.backups[backup_name]
        self.store = self.config.storage[self.backup.store].copy()

        self.db = DB()

        #    Find the run
        runs = self.db.runs(self.backup.name, run_date)
        if len(runs) == 0:
            raise Exception(_("Verify failed: Backup run does not exist"))
        self.vrun = runs[0]


    def run(self):

        self.test_store()
        #    Get config and packages
        self.fetch_config()

        #    We only check the data if there is actually something stored there.
        if self.vrun.nfiles == 0 and self.vrun.nfolders == 0:
            return True

        self.prepare_input(self.vrun, self.backup, self.store)
        try:
            #    Only check for tar data if there are files backed up
            #    Otherwise the tar will simply return an error
            tarinfo = self.tarfile.next()
            while tarinfo:
                tarinfo = self.tarfile.next()

        finally:
            self.close_input(self.backup)

        store_size, store_hash, = self.store_thread.get_hash()
        run_hash = self.vrun.hash
        run_size = self.vrun.size
        if store_size == run_size and store_hash == run_hash:
            return True
#        print(store_size, store_hash, run_size, run_hash)
        raise Exception(_("Verify failed - Run data is corrupt"))

    def test_store(self):
        store = self.config.storage[self.store.name].copy()
        store.connect()
        try:
            store.test()
        finally:
            store.disconnect()

    def fetch_config(self):
        store = self.config.storage[self.store.name].copy()
        store.connect()
        try:
            encrypted = False
            config = os.path.join(self.vrun.folder, const.ConfigName)
            if not store.exists(config):
                encrypted = True
                config = config + const.EncryptionSuffix
                if not store.exists(config):
                    raise Exception(_("Configuration file missing. Bad run"))

            store.get(config, os.path.join(tempfile.gettempdir(), "__vault__tmp__"))
            os.remove(os.path.join(tempfile.gettempdir(), "__vault__tmp__"))
            if self.backup.include_packages:
                packages = os.path.join(self.vrun.folder, const.PackageFile)
                if encrypted:
                    packages = packages + const.EncryptionSuffix
                store.get(packages, os.path.join(tempfile.gettempdir(), "__vault__tmp__"))
                os.remove(os.path.join(tempfile.gettempdir(), "__vault__tmp__"))
        finally:
            store.disconnect()

    def prepare_input(self, run, backup, store):
        '''
        Open the tar file.
        Connect the output of the tar to either:
        a) the storage handler
        b) to encryption (openssl), THEN the storage handler
        
        '''
        log.trace("Setting up input processes")

        #    Set up the encryptor (use TEE for now)
        self.crypt_proc = None
        if backup.encrypt:
            log.debug("Creating crypt objects")
            self.crypto = cryptor.DecryptStream(self.config.data_passphrase)
        else:
            self.crypto = cryptor.Buffer()

        #    Set up the storage handler
        log.debug("Starting storage thread")

#.........这里部分代码省略.........
开发者ID:tussock,项目名称:Vault,代码行数:101,代码来源:verify.py

示例15: setUp

    def setUp(self):
        self.config = Config.get_config()
        self.db = DB()
        self.db.check_upgrade()
        self.mark_db_ids()

        self.test_folder = tempfile.mkdtemp()
        self.files_folder = os.path.join(self.test_folder, "files")
        self.store_folder = os.path.join(self.test_folder, "store")
        self.restore_folder = os.path.join(self.test_folder, "restore")
        utils.makedirs(self.files_folder)
        utils.makedirs(self.store_folder)
        utils.makedirs(self.restore_folder)
        
        #    Build the base set of files
        with open(os.path.join(self.files_folder, "base"), "w") as f:
            f.write("base")

        with open(os.path.join(self.files_folder, "incr"), "w") as f:
            f.write("0")
            
        config_file = os.path.expanduser("~/.vault")
        if not os.path.exists(config_file):
            raise Exception("Vault test configuration file (~/.vault) does not exist")
        self.store_config = ConfigParser.RawConfigParser()
        self.store_config.read(config_file)

    #    FOLDER STORE
        self.store = FolderStore("teststore", "50MB", True, self.store_folder)
    #    DROPBOX STORE
#        self.login = self.store_config.get("DropBox", "login")
#        self.password = self.store_config.get("DropBox", "password")
#        self.folder = self.store_config.get("DropBox", "folder")
#        self.app_key = self.store_config.get("DropBox", "app_key")
#        self.app_secret_key = self.store_config.get("DropBox", "app_secret_key")
#        self.store = DropBoxStore("teststore", 0, False, self.folder, self.login, self.password,
#                                  self.app_key, self.app_secret_key)
    #    S3 STORE
#        self.key = self.store_config.get("Amazon", "aws_access_key_id")
#        self.secret_key = self.store_config.get("Amazon", "aws_secret_access_key")
#        self.bucket = self.store_config.get("Amazon", "bucket")
#        self.store = S3Store("teststore", 0, False, bucket=self.bucket, key=self.key, secret_key=self.secret_key)

        #    Now record the existance of this store
        self.config.storage[self.store.name] = self.store


        #    Build the backup object (dont save config)
        self.backup = Backup("testbackup")
        self.backup.include_folders = [self.files_folder]
        self.backup.store = self.store.name
        self.backup.notify_msg = False
        self.old_pass = self.config.data_passphrase
        self.config.data_passphrase = "goofy"
        self.backup.encrypt = True
        self.config.backups[self.backup.name] = self.backup

        #    build an options object for use with the backup
        self.options = BlankClass()
        self.options.dry_run = False
        self.options.message = False
        self.options.email = False
        self.options.shutdown = False
        self.options.norecurse = False
        
        #    How many cycles?
        self.cycles = 20
开发者ID:tussock,项目名称:Vault,代码行数:67,代码来源:test_longrun.py


注:本文中的lib.db.DB类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。