2016-02-13 41 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

啊对不起,我现在明白了。性能原因 –

回答

相关问题