當前位置: 首頁>>代碼示例>>Python>>正文


Python apsw.Connection方法代碼示例

本文整理匯總了Python中apsw.Connection方法的典型用法代碼示例。如果您正苦於以下問題:Python apsw.Connection方法的具體用法?Python apsw.Connection怎麽用?Python apsw.Connection使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在apsw的用法示例。


在下文中一共展示了apsw.Connection方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: openDB

# 需要導入模塊: import apsw [as 別名]
# 或者: from apsw import Connection [as 別名]
def openDB(self, dbfile_path = None, busytimeout = DEFAULT_BUSY_TIMEOUT):
        thread_name = threading.currentThread().getName()
        if thread_name in self.cursor_table:
            return self.cursor_table[thread_name]
        if dbfile_path.lower() != ':memory:':
            db_dir, db_filename = os.path.split(dbfile_path)
            if db_dir and not os.path.isdir(db_dir):
                os.makedirs(db_dir)
        con = apsw.Connection(dbfile_path)
        con.setbusytimeout(busytimeout)
        cur = con.cursor()
        self.cursor_table[thread_name] = cur
        if not self.applied_pragma_sync_norm:
            self.applied_pragma_sync_norm = True
            cur.execute('PRAGMA synchronous = NORMAL;')
        return cur 
開發者ID:alesnav,項目名稱:p2ptv-pi,代碼行數:18,代碼來源:sqlitecachedb.py

示例2: __init__

# 需要導入模塊: import apsw [as 別名]
# 或者: from apsw import Connection [as 別名]
def __init__(self, bot):
		self.bot = bot
		self.ignore_cache = {}
		self.config = Config.get_conf(self, identifier=7345167905)
		self.config.register_guild(
			enableGuild = True,
			disabledChannels = [],
			displayStopwords = True
		)
		self._connection = apsw.Connection(str(cog_data_path(self) / 'wordstats.db'))
		self.cursor = self._connection.cursor()
		self.cursor.execute('PRAGMA journal_mode = wal;')
		self.cursor.execute('PRAGMA read_uncommitted = 1;')
		self.cursor.execute(
			'CREATE TABLE IF NOT EXISTS member_words ('
			'guild_id INTEGER NOT NULL,'
			'user_id INTEGER NOT NULL,'
			'word TEXT NOT NULL,'
			'quantity INTEGER DEFAULT 1,'
			'PRIMARY KEY (guild_id, user_id, word)'
			');'
		)
		self._executor = concurrent.futures.ThreadPoolExecutor(1) 
開發者ID:Flame442,項目名稱:FlameCogs,代碼行數:25,代碼來源:wordstats.py

示例3: command_restore

# 需要導入模塊: import apsw [as 別名]
# 或者: from apsw import Connection [as 別名]
def command_restore(self, cmd):
        """restore ?DB? FILE: Restore database from FILE into DB (default "main")

        Copies the contents of FILE to the current database (default "main").
        The backup is done at the page level - SQLite copies the pages as
        is.  There is no round trip through SQL code.
        """
        dbname="main"
        if len(cmd)==1:
            fname=cmd[0]
        elif len(cmd)==2:
            dbname=cmd[0]
            fname=cmd[1]
        else:
            raise self.Error("Restore takes one or two parameters")
        input=apsw.Connection(fname)
        b=self.db.backup(dbname, input, "main")
        try:
            while not b.done:
                b.step()
        finally:
            b.finish()
            input.close() 
開發者ID:plasticityai,項目名稱:magnitude,代碼行數:25,代碼來源:shell.py

示例4: __init__

# 需要導入模塊: import apsw [as 別名]
# 或者: from apsw import Connection [as 別名]
def __init__(self, path=None, read_only=False):
        if path is None:
            path = config.database_path
        if read_only:
            flags = apsw.SQLITE_OPEN_READONLY
        else:
            flags = apsw.SQLITE_OPEN_CREATE | apsw.SQLITE_OPEN_READWRITE

        # The global lock is acquired in the constructor, so you must never instantiate a DbCursor
        # object without actually using it.
        global_database_lock.acquire()

        try:
            # The connection setup must be done in the constructor, NOT in __enter__.
            # If __enter__ raises an exception, then the __exit__ method will also be called.
            self.connection = apsw.Connection(path, flags)
            self.connection.setbusytimeout(5000)
            for module in apply_filters("database-vtmodules", [self.get_assignments_vtmodule()]):
                module.registerWithConnection(self.connection)
        except Exception:
            global_database_lock.release()
            raise 
開發者ID:octobear2,項目名稱:ob2,代碼行數:24,代碼來源:__init__.py

示例5: initializer

# 需要導入模塊: import apsw [as 別名]
# 或者: from apsw import Connection [as 別名]
def initializer(log, _path, _ledger_name, query_timeout, _measure=False, block_and_filter=None):
    db = apsw.Connection(_path, flags=apsw.SQLITE_OPEN_READONLY | apsw.SQLITE_OPEN_URI)
    db.setrowtrace(row_factory)
    if block_and_filter:
        blocked_streams, blocked_channels, filtered_streams, filtered_channels = block_and_filter
    else:
        blocked_streams = blocked_channels = filtered_streams = filtered_channels = {}
    ctx.set(
        ReaderState(
            db=db, stack=[], metrics={}, is_tracking_metrics=_measure,
            ledger=Ledger if _ledger_name == 'mainnet' else RegTestLedger,
            query_timeout=query_timeout, log=log,
            blocked_streams=blocked_streams, blocked_channels=blocked_channels,
            filtered_streams=filtered_streams, filtered_channels=filtered_channels,
        )
    ) 
開發者ID:lbryio,項目名稱:lbry-sdk,代碼行數:18,代碼來源:reader.py

示例6: open

# 需要導入模塊: import apsw [as 別名]
# 或者: from apsw import Connection [as 別名]
def open(self):
        self.db = apsw.Connection(
            self._db_path,
            flags=(
                apsw.SQLITE_OPEN_READWRITE |
                apsw.SQLITE_OPEN_CREATE |
                apsw.SQLITE_OPEN_URI
            )
        )
        def exec_factory(cursor, statement, bindings):
            tpl = namedtuple('row', (d[0] for d in cursor.getdescription()))
            cursor.setrowtrace(lambda cursor, row: tpl(*row))
            return True
        self.db.setexectrace(exec_factory)
        self.execute(self.PRAGMAS)
        self.execute(self.CREATE_TABLES_QUERY)
        register_canonical_functions(self.db)
        self.state_manager = Manager()
        self.blocked_streams = self.state_manager.dict()
        self.blocked_channels = self.state_manager.dict()
        self.filtered_streams = self.state_manager.dict()
        self.filtered_channels = self.state_manager.dict()
        self.update_blocked_and_filtered_claims()
        for algorithm in self.trending:
            algorithm.install(self.db) 
開發者ID:lbryio,項目名稱:lbry-sdk,代碼行數:27,代碼來源:writer.py

示例7: responseToDB

# 需要導入模塊: import apsw [as 別名]
# 或者: from apsw import Connection [as 別名]
def responseToDB(self):
        time.sleep(3)
        count = 0
        while True:
            resp = self.q.get()
            if resp == None:
                break
            else:
                if self.resp_db != None:
                    self.resp_db.insert_result(resp)
                    self.requestToDB(resp.respID) #Insert the request
                    count = self.resp_db.get_count()
                no_rq = self.rLsize - self.rq_toscan.qsize()
                printdata = 'Responses: '+ str(count) +'\t\tRequests: '+str(no_rq)
                print(printdata, end='\r', flush=True)
        print('\nScan Completed!')
        if self.dbname != None:
            backupdb = apsw.Connection(self.dbname)
            print('Saving results to '+self.dbname)
            with backupdb.backup("main", self.resp_db.conn, "main") as b:
                while not b.done:
                    b.step(100)
    
    #This stores requests to the DB 
開發者ID:maK-,項目名稱:scanomaly,代碼行數:26,代碼來源:requestEngine.py

示例8: _connect

# 需要導入模塊: import apsw [as 別名]
# 或者: from apsw import Connection [as 別名]
def _connect(self, database, **kwargs):
        conn = apsw.Connection(database, **kwargs)
        if self.timeout is not None:
            conn.setbusytimeout(self.timeout)
        try:
            self._add_conn_hooks(conn)
        except:
            conn.close()
            raise
        return conn 
開發者ID:danielecook,項目名稱:Quiver-alfred,代碼行數:12,代碼來源:apsw_ext.py

示例9: sqlite3_connection

# 需要導入模塊: import apsw [as 別名]
# 或者: from apsw import Connection [as 別名]
def sqlite3_connection(*args, **kwargs):
    """SQLite3 connection context manager.  On exit, runs close."""
    connection = apsw.Connection(*args, **kwargs)
    try:
        yield connection
    finally:
        connection.close() 
開發者ID:probcomp,項目名稱:bayeslite,代碼行數:9,代碼來源:sqlite3_util.py

示例10: __init__

# 需要導入模塊: import apsw [as 別名]
# 或者: from apsw import Connection [as 別名]
def __init__(self, cookie, pathname=None, seed=None, version=None,
            compatible=None):
        if cookie != bayesdb_open_cookie:
            raise ValueError('Do not construct BayesDB objects directly!')
        if pathname is None:
            pathname = ":memory:"
        self.pathname = pathname
        self._sqlite3 = apsw.Connection(pathname)
        self._txn_depth = 0     # managed in txn.py
        self._cache = None      # managed in txn.py
        self.backends = {}
        self.tracer = None
        self.sql_tracer = None
        self.temptable = 0
        self.qid = 0
        if seed is None:
            seed = struct.pack('<QQQQ', 0, 0, 0, 0)
        self._prng = weakprng.weakprng(seed)
        pyrseed = self._prng.weakrandom32()
        self._py_prng = random.Random(pyrseed)
        nprseed = [self._prng.weakrandom32() for _ in range(4)]
        self._np_prng = numpy.random.RandomState(nprseed)

        # Set up or check the permanent schema on disk.
        schema.bayesdb_install_schema(self, version=version,
            compatible=compatible)

        # Set up the in-memory BQL functions and virtual tables that
        # need not have storage on disk.
        bqlfn.bayesdb_install_bql(self._sqlite3, self)
        self._sqlite3.createmodule('bql_mutinf', bqlvtab.MutinfModule(self))
        self._sqlite3.cursor().execute(
            'create virtual table temp.bql_mutinf using bql_mutinf')

        # Set up math utilities.
        bqlmath.bayesdb_install_bqlmath(self._sqlite3, self)

        # Cache an empty cursor for convenience.
        empty_cursor = self._sqlite3.cursor()
        empty_cursor.execute('')
        self._empty_cursor = bql.BayesDBCursor(self, empty_cursor) 
開發者ID:probcomp,項目名稱:bayeslite,代碼行數:43,代碼來源:bayesdb.py

示例11: reconnect

# 需要導入模塊: import apsw [as 別名]
# 或者: from apsw import Connection [as 別名]
def reconnect(self):
        """Reconnecting may sometimes be necessary, e.g. before a DROP TABLE"""
        # http://stackoverflow.com/questions/32788271
        if self.pathname == ":memory:":
            raise ValueError("""Cannot meaningfully reconnect to an in-memory
                database. All prior transactions would be lost.""")
        assert self._txn_depth == 0, "pending BayesDB transactions"
        self._sqlite3.close()
        self._sqlite3 = apsw.Connection(self.pathname) 
開發者ID:probcomp,項目名稱:bayeslite,代碼行數:11,代碼來源:bayesdb.py

示例12: __init__

# 需要導入模塊: import apsw [as 別名]
# 或者: from apsw import Connection [as 別名]
def __init__(self, bot: Red):
        self.bot = bot
        self._connection = apsw.Connection(str(cog_data_path(self) / "MartTools.db"))
        self.cursor = self._connection.cursor()
        self.cursor.execute(PRAGMA_journal_mode)
        self.cursor.execute(PRAGMA_wal_autocheckpoint)
        self.cursor.execute(PRAGMA_read_uncommitted)
        self.cursor.execute(CREATE_TABLE_PERMA)
        self.cursor.execute(DROP_TEMP)
        self.cursor.execute(CREATE_TABLE_TEMP)
        self.uptime = datetime.utcnow()
        self.cursor.execute(INSERT_PERMA_DO_NOTHING, (-1000, "creation_time", time.time())) 
開發者ID:PredaaA,項目名稱:predacogs,代碼行數:14,代碼來源:marttools.py

示例13: _ensure_db

# 需要導入模塊: import apsw [as 別名]
# 或者: from apsw import Connection [as 別名]
def _ensure_db(self):
        "The database isn't opened until first use.  This function ensures it is now open."
        if not self._db:
            if not self.dbfilename:
                self.dbfilename=":memory:"
            self._db=apsw.Connection(self.dbfilename, flags=apsw.SQLITE_OPEN_URI | apsw.SQLITE_OPEN_READWRITE | apsw.SQLITE_OPEN_CREATE)
        return self._db 
開發者ID:plasticityai,項目名稱:magnitude,代碼行數:9,代碼來源:shell.py

示例14: command_backup

# 需要導入模塊: import apsw [as 別名]
# 或者: from apsw import Connection [as 別名]
def command_backup(self, cmd):
        """backup ?DB? FILE: Backup DB (default "main") to FILE

        Copies the contents of the current database to FILE
        overwriting whatever was in FILE.  If you have attached databases
        then you can specify their name instead of the default of "main".

        The backup is done at the page level - SQLite copies the pages
        as is.  There is no round trip through SQL code.
        """
        dbname="main"
        if len(cmd)==1:
            fname=cmd[0]
        elif len(cmd)==2:
            dbname=cmd[0]
            fname=cmd[1]
        else:
            raise self.Error("Backup takes one or two parameters")
        out=apsw.Connection(fname)
        b=out.backup("main", self.db, dbname)
        try:
            while not b.done:
                b.step()
        finally:
            b.finish()
            out.close() 
開發者ID:plasticityai,項目名稱:magnitude,代碼行數:28,代碼來源:shell.py

示例15: handle_interrupt

# 需要導入模塊: import apsw [as 別名]
# 或者: from apsw import Connection [as 別名]
def handle_interrupt(self):
        """Deal with keyboard interrupt (typically Control-C).  It
        will :meth:`~Connection.interrupt` the database and print"^C" if interactive."""
        self.db.interrupt()
        if not self.bail and self.interactive:
            self.write(self.stderr, "^C\n")
            return
        raise 
開發者ID:plasticityai,項目名稱:magnitude,代碼行數:10,代碼來源:shell.py


注:本文中的apsw.Connection方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。