2016-02-13 58 views
1

我正在寫一個python方法來轉儲MySQL表的全部內容。但是,此表包含個人身份信息(PII)。我有一個要求,這個數據必須是GPG加密的。此外,要求是不允許將這些數據以未加密的形式寫入磁盤(即使這只是稍後刪除的臨時文件)如何將MySQLdb的fetchall()的輸出轉換爲文件流?

我已經通過使用subprocess.Popen()暫時解決了此問題,並且管道將mysql可執行文件的直接輸出到gpg可執行文件,然後將該輸出管道到stdout:

p1 = subprocess.Popen(
     'mysql -h127.0.0.1 -Dmydbinstance -umyuser -pmyPassword -e "select * from my_table"', 
     stdin=subprocess.PIPE, 
     stdout=subprocess.PIPE, 
    ) 

    p2 = subprocess.Popen(
     "gpg --encrypt -r [email protected]", 
     stdin=p1.stdout, 
     stdout=subprocess.PIPE 
    ) 

    p1.stdout.close() 
    print p2.communicate()[0] 

它的工作原理,但在我看來,像一個可怕的黑客。 fork shell進程做這件事感覺非常錯誤。

所以我想在python本地執行此操作(沒有popen())。我有一個到數據庫的MySQLdb連接。而python-gnupg模塊可以對文件流進行加密。但是,我怎樣才能將MySQLdb的fetchall()的輸出轉換爲文件流呢?到目前爲止,我已經是這樣的:

import MySQLdb 
import gpg 

DBConn = MySQLdb.Connect(host='127.0.0.1', user='myuser', passwd='myPassword', db='mydbinstance', port=3306, charset='utf8') 
DBConn.autocommit(True) 
cur = DBConn.cursor(MySQLdb.cursors.DictCursor) 
cur.execute("select * from my_table") 
if cur.rowcount >= 1: 
    rows = cur.fetchall() 
else 
    rows = [] 
for i in rows: 
    print i 

# WHAT DO I NEED TO DO HERE TO TURN THE DB OUTPUT INTO A FILE STREAM? 

encrypted_ascii_data = gpg.encrypt_file(stream, recipient_fingerprint) 

我怎麼能拒絕使用fetchall()的輸出到一個文件流,這樣我可以把它送到gpg.encrypt_file()無需編寫臨時文件磁盤未加密?可能有數百萬行數據。因此,將它一次全部讀入記憶中並不是一個可行的解決方案。

+1

爲什麼不能使用'encrypt'而不是'encrypt_file'? –

+1

啊對不起,我現在明白了。性能原因 –

回答

相關問題