本文整理汇总了Python中pysqlcipher.dbapi2.connect函数的典型用法代码示例。如果您正苦于以下问题:Python connect函数的具体用法?Python connect怎么用?Python connect使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了connect函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: decrypt
def decrypt( key ,operation):
if operation==1:
conn = sqlite.connect( ORIGINAL_FILE )
else:
conn = sqlite.connect( DECRYPTED_FILE )
c = conn.cursor()
try:
if operation==1:
c.execute( "PRAGMA key = '" + key + "';" )
c.execute( "PRAGMA cipher_use_hmac = OFF;" )
c.execute( "PRAGMA cipher_page_size = 1024;" )
c.execute( "PRAGMA kdf_iter = 4000;" )
c.execute( "ATTACH DATABASE '"+DECRYPTED_FILE+"' AS wechatdecrypted KEY '';" )
c.execute( "SELECT sqlcipher_export( 'wechatdecrypted' );" )
c.execute( "DETACH DATABASE wechatdecrypted;" )
else:
c.execute( "ATTACH DATABASE '"+ENCRYPTED_FILE_NEW+"' AS wechatencrypted KEY '"+ key +"';" )
c.execute( "PRAGMA wechatencrypted.cipher_use_hmac = OFF;" )
c.execute( "PRAGMA wechatencrypted.cipher_page_size = 1024;" )
c.execute( "PRAGMA wechatencrypted.kdf_iter = 4000;" )
c.execute( "SELECT sqlcipher_export( 'wechatencrypted' );" )
c.execute( "DETACH DATABASE wechatencrypted;" )
c.close()
status = 1
except:
c.close()
status = 0
return status
示例2: init_db
def init_db():
# Initialize in-memory database
app_db = sqlcipher.connect(':memory:', check_same_thread = False)
# Connect to disk-based database and use key
db = sqlcipher.connect(app.config['DB'])
db.executescript('pragma key = "{}"'.format(app.config['KEY']))
# Copy database to memory
app_db.executescript(''.join(line for line in db.iterdump()))
return app_db
示例3: CheckSetIsolationLevel
def CheckSetIsolationLevel(self):
"""
See issue 3312.
"""
con = sqlite.connect(":memory:")
self.assertRaises(UnicodeEncodeError, setattr, con,
"isolation_level", u"\xe9")
示例4: db_connect
def db_connect(password):
db = dbapi2.connect(path(app.config['DB_NAME']))
# TODO: Use something better than re.escape for this
# For some reason, normal '?' placeholders don't work for PRAGMA's
db.execute("PRAGMA key = '%s'" % re.escape(password))
db.execute("PRAGMA foreign_keys = ON")
return db
示例5: CheckAutoCommit
def CheckAutoCommit(self):
"""
Verifies that creating a connection in autocommit mode works.
2.5.3 introduced a regression so that these could no longer
be created.
"""
con = sqlite.connect(":memory:", isolation_level=None)
示例6: getDecryptFile
def getDecryptFile(db, key, fileIn, fileOut ):
status = False
if not os.path.isfile(fileOut):
#
# code source: http://articles.forensicfocus.com/2014/10/01/decrypt-wechat-enmicromsgdb-database/
#
conn = sqlite3.connect( u'%s' % fileIn )
conn.row_factory = sqlite3.Row
cur = conn.cursor()
if setDecryptParams(cur, key):
try:
print( u'Decrypting...' )
cur.execute( 'ATTACH DATABASE "%s" AS wechatdecrypted KEY "";' % fileOut)
cur.execute( 'SELECT sqlcipher_export( "wechatdecrypted" );' )
cur.execute( 'DETACH DATABASE wechatdecrypted;' )
print( u'Detaching database...' )
cur.close()
status = True
except:
print(u'Decrypting failed!')
pass
cur.close()
return(status)
示例7: _open_database
def _open_database(cls, sqlite_file, password, document_factory=None,
soledad=None):
if not os.path.isfile(sqlite_file):
raise errors.DatabaseDoesNotExist()
tries = 2
while True:
# Note: There seems to be a bug in sqlite 3.5.9 (with python2.6)
# where without re-opening the database on Windows, it
# doesn't see the transaction that was just committed
db_handle = dbapi2.connect(sqlite_file)
SQLCipherDatabase.set_pragma_key(db_handle, password)
c = db_handle.cursor()
v, err = cls._which_index_storage(c)
db_handle.close()
if v is not None:
break
# possibly another process is initializing it, wait for it to be
# done
if tries == 0:
raise err # go for the richest error?
tries -= 1
time.sleep(cls.WAIT_FOR_PARALLEL_INIT_HALF_INTERVAL)
return SQLCipherDatabase._sqlite_registry[v](
sqlite_file, password, document_factory=document_factory,
soledad=soledad)
示例8: setUp
def setUp(self):
self.cx = sqlite.connect(":memory:")
self.cx.execute("create table test(id integer primary key, blob_col blob)")
self.blob_data = "a" * 100
self.cx.execute("insert into test(blob_col) values (?)", (self.blob_data, ))
self.blob = self.cx.blob("test", "blob_col", 1, 1)
self.second_data = "b" * 100
示例9: encrypt
def encrypt(args):
print
print yellow('Generating key...')
key = _generate_key(args.imei, args.uin)
print
print green('=' * 80)
print green('The key is:')
print
print cyan(' %s' % key)
print
print yellow('Encrypting, hang on...')
_delete_file_if_exists(args.output_file)
conn = sqlite.connect(args.input_file)
c = conn.cursor()
try:
c.execute('PRAGMA cipher_default_use_hmac = OFF;')
c.execute('ATTACH DATABASE \'%s\' AS encrypted KEY \'%s\';' % (args.output_file, key))
c.execute('PRAGMA cipher_use_hmac = OFF;')
c.execute('SELECT sqlcipher_export(\'encrypted\');')
c.execute('DETACH DATABASE encrypted;')
except:
print
print red('=' * 80)
print red('An error occurred.')
sys.exit(1)
else:
print
print green('=' * 80)
print green('Success!')
finally:
c.close()
示例10: test__open_database_during_init
def test__open_database_during_init(self):
temp_dir = self.createTempDir(prefix='u1db-test-')
path = temp_dir + '/initialised.db'
db = sqlite_backend.SQLitePartialExpandDatabase.__new__(
sqlite_backend.SQLitePartialExpandDatabase)
db._db_handle = dbapi2.connect(path) # db is there but not yet init-ed
self.addCleanup(db.close)
observed = []
class SQLiteDatabaseTesting(sqlite_backend.SQLiteDatabase):
WAIT_FOR_PARALLEL_INIT_HALF_INTERVAL = 0.1
@classmethod
def _which_index_storage(cls, c):
res = super(SQLiteDatabaseTesting, cls)._which_index_storage(c)
db._ensure_schema() # init db
observed.append(res[0])
return res
db2 = SQLiteDatabaseTesting._open_database(path)
self.addCleanup(db2.close)
self.assertIsInstance(db2, sqlite_backend.SQLitePartialExpandDatabase)
self.assertEqual(
[None,
sqlite_backend.SQLitePartialExpandDatabase._index_storage_value],
observed)
示例11: __GET_STATUS
def __GET_STATUS(self):
status = ""
try:
conn = sqlite3.connect(
path_constants.installation + '/stats.db', timeout=10)
except:
pass
try:
cur = conn.cursor()
cur.execute("PRAGMA key='f$$pm->>>'")
status = cur.execute("select error from errors where ptid='%s' and accession='%s' and series='%s'" %
(self.__patient.ID, self.__patient.AccessionNumber, self.__patient.SeriesDescription)).fetchall()[0][0]
conn.close()
except IndexError:
print "Not processed before."
conn.close()
except Exception as exc:
print "Problem reading status: %s" % exc
conn.close()
if(status
and (re.findall("error", status, flags=re.IGNORECASE)
or re.findall("problem", status, flags=re.IGNORECASE))):
print "Already processed, but with errors."
self.__set_state(STATES.FS)
elif(status and re.findall("Already processed", status, flags=re.IGNORECASE)):
print "Already processed without errors, but attempted reprocessed before."
self.__set_state(STATES.FS)
# Not procssed
elif(not status):
self.__set_state(STATES.FS)
else:
self.__success = "Already processed."
self.__set_state(STATES.QUITTING)
示例12: CheckCollationIsUsed
def CheckCollationIsUsed(self):
if sqlite.version_info < (3, 2, 1): # old SQLite versions crash on this test
return
def mycoll(x, y):
# reverse order
return -cmp(x, y)
con = sqlite.connect(":memory:")
con.create_collation("mycoll", mycoll)
sql = """
select x from (
select 'a' as x
union
select 'b' as x
union
select 'c' as x
) order by x collate mycoll
"""
result = con.execute(sql).fetchall()
if result[0][0] != "c" or result[1][0] != "b" or result[2][0] != "a":
self.fail("the expected order was not returned")
con.create_collation("mycoll", None)
try:
result = con.execute(sql).fetchall()
self.fail("should have raised an OperationalError")
except sqlite.OperationalError, e:
self.assertEqual(e.args[0].lower(), "no such collation sequence: mycoll")
示例13: CheckCreateCollationNotCallable
def CheckCreateCollationNotCallable(self):
con = sqlite.connect(":memory:")
try:
con.create_collation("X", 42)
self.fail("should have raised a TypeError")
except TypeError, e:
self.assertEqual(e.args[0], "parameter must be callable")
示例14: CheckCreateCollationNotAscii
def CheckCreateCollationNotAscii(self):
con = sqlite.connect(":memory:")
try:
con.create_collation("collä", cmp)
self.fail("should have raised a ProgrammingError")
except sqlite.ProgrammingError, e:
pass
示例15: test__open_database_during_init
def test__open_database_during_init(self):
temp_dir = self.createTempDir(prefix='u1db-test-')
path = temp_dir + '/initialised.db'
db = SQLCipherDatabase.__new__(
SQLCipherDatabase)
db._db_handle = dbapi2.connect(path) # db is there but not yet init-ed
db._syncers = {}
c = db._db_handle.cursor()
c.execute('PRAGMA key="%s"' % PASSWORD)
self.addCleanup(db.close)
observed = []
class SQLiteDatabaseTesting(SQLCipherDatabase):
WAIT_FOR_PARALLEL_INIT_HALF_INTERVAL = 0.1
@classmethod
def _which_index_storage(cls, c):
res = SQLCipherDatabase._which_index_storage(c)
db._ensure_schema() # init db
observed.append(res[0])
return res
db2 = SQLiteDatabaseTesting._open_database(path, PASSWORD)
self.addCleanup(db2.close)
self.assertIsInstance(db2, SQLCipherDatabase)
self.assertEqual(
[None,
SQLCipherDatabase._index_storage_value],
observed)