2013-03-16 38 views
1

我需要一種方法來訪問我的python3應用程序在內存中(':memory:')在命令行界面工具sqlite3中創建的數據庫。這個想法是爲用戶提供標準sqlite3工具的便利,而不是在python本身中重新實現sqlite shell。在python和sqlite3之間傳輸數據庫cli工具

同樣,我們的目標是:

數據庫中存儲在我的python程序打開 - >編輯/處理在sqlite3的CLI工具數據庫 - >移動的(可能)修改的數據庫回我Python程序。

我試着向:

def sqlite_cli(self): 
    # Spawn the original sqlite3 cli interface 
    # Dump the database in a named temporary file. Read it back into 
    # memory. At close() the tempfile will be erased. 
    with tempfile.NamedTemporaryFile(delete=True) as tf: 
     for line in self.connection.iterdump(): 
      tf.write(bytes(line, 'ascii')) 

     # Work with the database through sqlite3 
     subprocess.call(['sqlite3', '-init', tf.name]) 

     # Read the potentially modified database 
     # !!!!!!!!!!!!!!!! 
     # Here happens the logic gap: The sqlite3 tool doesn't 
     # save modifications to the file opend as the -init argument. 
     # How can I save the modifications done within sqlite3 as a 
     # sql text file ready to be read back into the app?! 
     tf.seek(0) 
     edited_db = tf.read() 

     # Delete all tables residing in memory 
     try: 
      for t in ACCMAN_TABLES: 
       self.cursor.execute('DROP TABLE IF EXISTS %s' % t) 
      self.connection.commit() 
      # Add the (maybe) edited one 
      self.cursor.executescript(edited_db.decode(encoding='utf-8')) 
      self.connection.commit() 
     except sqlite3.Error as e: 
      logger.error("sqlite_cli(): %s" % e.args[0]) 

     tf.close() 

在這種情況下,我需要一種方法來保存源碼-init名無論是在SQL或二進制打開的數據庫上進行的所有修改(在正常的...)格式。

編輯:一個解決辦法是讓用戶對數據庫做他的東西,然後他結束會話(.Q .quit .exit捕捉標準輸入)之前,我可以把一箇中介

.output outfile.sql 
.dump 
.quit 

在文件系統上重定向整個數據庫(以及它的修改!),然後將創建的文件讀回python應用程序。但是,這是如此醜陋和不雅...

+4

爲什麼要將數據庫保存在內存中?首先在臨時文件中打開它,並且讓Python和'sqlite3'交替使用同一個文件是不是更容易? – millimoose 2013-03-16 12:55:58

+0

因爲在腳本本身旁邊不應該有任何文件。應用程序的目的是從腳本文件本身提取數據庫(aes encrypted和base64編碼)並將其讀入內存。數據庫中的信息非常敏感,不應該保存在文件系統中。 – 2013-03-21 09:11:51

+0

在這種情況下,將數據庫轉儲到SQL文件中的建議令人困惑。在第一個建議的解決方案中使用'NamedTemporaryFile'也一樣。兩者具有完全相同的安全含義。 – millimoose 2013-03-21 10:03:54

回答

0

我不認爲你會喜歡這個答案,但我會考慮在你的應用程序中編寫「模型」作爲能夠接收XML的「服務器」 -rpc電話。這樣,您的「控制器」(以及外部控制器)就可以訪問數據庫並執行您允許他們執行的任何操作。將類的方法作爲XML-RPC服務器公開很容易。請參閱http://docs.python.org/2/library/xmlrpclib.html?highlight=xmlrpc#xmlrpclib