本文整理汇总了Python中pysqlcipher.dbapi2.connect函数的典型用法代码示例。如果您正苦于以下问题:Python connect函数的具体用法?Python connect怎么用?Python connect使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了connect函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
开发者ID:lixingcong,项目名称:lixingcong.github.io,代码行数:28,代码来源:fmd_wechatdecipher.py
示例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
开发者ID:CBIIT,项目名称:nci-analysis-tools-glossary,代码行数:12,代码来源:CancerTerms.py
示例3: CheckSetIsolationLevel
def CheckSetIsolationLevel(self):
"""
See issue 3312.
"""
con = sqlite.connect(":memory:")
self.assertRaises(UnicodeEncodeError, setattr, con,
"isolation_level", u"\xe9")
开发者ID:02strich,项目名称:pysqlcipher,代码行数:7,代码来源:regression.py
示例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
开发者ID:uppfinnarn,项目名称:SecretBooru,代码行数:7,代码来源:secretbooru.py
示例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)
开发者ID:02strich,项目名称:pysqlcipher,代码行数:7,代码来源:regression.py
示例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)
开发者ID:SeraphLiu,项目名称:wechatvoice,代码行数:26,代码来源:EnMicroMsgDB.py
示例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)
开发者ID:isislovecruft,项目名称:soledad,代码行数:25,代码来源:sqlcipher.py
示例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
开发者ID:leapcode,项目名称:pysqlcipher,代码行数:7,代码来源:dbapi.py
示例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()
开发者ID:jrdietrick,项目名称:wechat-tools,代码行数:31,代码来源:main.py
示例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)
开发者ID:MeanderingCode,项目名称:soledad,代码行数:26,代码来源:test_sqlite_backend.py
示例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)
开发者ID:wonkykludge,项目名称:fsspmnl,代码行数:35,代码来源:process.py
示例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")
开发者ID:02strich,项目名称:pysqlcipher,代码行数:28,代码来源:hooks.py
示例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")
开发者ID:02strich,项目名称:pysqlcipher,代码行数:7,代码来源:hooks.py
示例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
开发者ID:02strich,项目名称:pysqlcipher,代码行数:7,代码来源:hooks.py
示例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)
开发者ID:fbernitt,项目名称:soledad,代码行数:29,代码来源:test_sqlcipher.py
示例16: CheckFailedOpen
def CheckFailedOpen(self):
YOU_CANNOT_OPEN_THIS = "/foo/bar/bla/23534/mydb.db"
try:
con = sqlite.connect(YOU_CANNOT_OPEN_THIS)
except sqlite.OperationalError:
return
self.fail("should have raised an OperationalError")
开发者ID:leapcode,项目名称:pysqlcipher,代码行数:7,代码来源:dbapi.py
示例17: _decrpyt
def _decrpyt(src, dst, key, cipher, kdf_iter, cipher_page_size):
conn = sqlite.connect(src)
c = conn.cursor()
c.execute("PRAGMA key='{0}'".format(key))
if kdf_iter is not None:
c.execute("PRAGMA kdf_iter={0}".format(kdf_iter))
if cipher is not None:
c.execute("PRAGMA cipher='{0}'".format(cipher))
if cipher_page_size is not None:
c.execute("PRAGMA cipher_page_size={0}".format(cipher_page_size))
c.close()
c = conn.cursor()
try:
c.execute('SELECT COUNT(*) from sqlite_master')
count = c.fetchone()[0]
except sqlite.DatabaseError as ex:
print('wrong key: {0}'.format(ex))
sys.exit(1)
finally:
c.close()
c = conn.cursor()
c.execute("ATTACH DATABASE '{0}' AS plaintext KEY ''".format(dst))
c.execute("SELECT sqlcipher_export('plaintext');")
c.execute("DETACH DATABASE plaintext")
c.close()
开发者ID:arthepsy,项目名称:misc,代码行数:27,代码来源:sqlcipher_migrate.py
示例18: _connect
def _connect(self):
params = dict(self.connect_params)
passphrase = params.pop('passphrase', '')
kdf_iter = params.pop('kdf_iter', 64000)
if len(passphrase) < 8:
raise ImproperlyConfigured(
'SqlCipherDatabase passphrase should be at least eight '
'character long.')
if kdf_iter and kdf_iter < 10000:
raise ImproperlyConfigured(
'SqlCipherDatabase kdf_iter should be at least 10000.')
conn = sqlcipher.connect(self.database, **params)
conn.isolation_level = None
try:
conn.execute(
'PRAGMA key=\'{0}\''.format(passphrase.replace("'", "''")))
conn.execute('PRAGMA kdf_iter={0:d}'.format(kdf_iter))
self._add_conn_hooks(conn)
except:
conn.close()
raise
else:
return conn
开发者ID:asoucase,项目名称:peewee,代码行数:26,代码来源:sqlcipher_ext.py
示例19: getFuncTemplate
def getFuncTemplate(db, decrypted=True, key=None):
results = []
# Create query
query = 'SELECT * FROM friend_ext;'
# Open database, set up cursor to read database
conn = sqlite3.connect(db)
conn.row_factory = sqlite3.Row
cur = conn.cursor()
if not decrypted:
if not setDecryptParams(cur, key):
cur.close()
return(result)
# Execute query
cur.execute(query)
try:
for index, row in enumerate(cur):
pass
except:
pass
cur.close()
return(results)
开发者ID:SeraphLiu,项目名称:wechatvoice,代码行数:27,代码来源:EnMicroMsgDB.py
示例20: CheckConnectionExecutemany
def CheckConnectionExecutemany(self):
con = sqlite.connect(":memory:")
con.execute("create table test(foo)")
con.executemany("insert into test(foo) values (?)", [(3,), (4,)])
result = con.execute("select foo from test order by foo").fetchall()
self.assertEqual(result[0][0], 3, "Basic test of Connection.executemany")
self.assertEqual(result[1][0], 4, "Basic test of Connection.executemany")
开发者ID:leapcode,项目名称:pysqlcipher,代码行数:7,代码来源:dbapi.py
注:本文中的pysqlcipher.dbapi2.connect函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论