1

コマンド ライン インターフェイス ツール sqlite3 で、メモリ内の python3 アプリケーションで作成されたデータベース (':memory:') にアクセスする方法が必要です。アイデアは、Python 自体で sqlite シェルを再実装する代わりに、標準の sqlite3 ツールの利便性をユーザーに提供することです。

繰り返しますが、目標は次のとおりです。

メモリ内の私の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()

この場合、sqlite -init filenameで開かれたデータベースで行われたすべての変更を、ファイルシステム上の sql またはバイナリ (通常の形式...) 形式で保存する方法が必要です。

編集:1つの解決策は、ユーザーにデータベースで自分のことをさせてから、セッションを終了する前に(.q .quit .exitのstdinをキャプチャする)、仲介者を送ることができます

.output outfile.sql
.dump
.quit

ファイルシステム上のデータベース全体(およびそれは変更です!)をリダイレクトし、作成されたファイルをPythonアプリに読み込みます。しかし、これはとても醜く、エレガントではありません...

4

1 に答える 1

0

この回答を気に入っていただけるとは思いませんが、アプリの「モデル」を xml-rpc 呼び出しを受信できる「サーバー」として記述することを検討します。このようにして、「コントローラー」(および外部コントローラー)はデータベースにアクセスし、許可されていることは何でも実行できます。クラスのメソッドを XML-RPC サーバーとして公開するのは非常に簡単です。http://docs.python.org/2/library/xmlrpclib.html?highlight=xmlrpc#xmlrpclibを参照してください。

于 2013-08-23T20:46:36.467 に答える