错误:期望 str、bytes 或 os.PathLike 对象,而非 StorageStreamDownloader - 使用 Python 解密 blob 文件的 pgp
我正在尝试从Azure Blob存储中读取一个加密的csv文件,并使用gnupg进行解密,然后在Python中读取它。我可以访问这个blob文件,但当我把它传递给解密函数时,它报错了。
错误信息:期望的是字符串、字节或os.PathLike对象,而不是StorageStreamDownloader。
这个blob文件是StorageStreamDownloader类型。当我把它转换成字节时,我得到了“嵌入的空字节”错误。
有人能帮我解决这个问题吗?下面是我的代码。
from azure.storage.blob import BlobServiceClient, BlobClient
import pandas as pd
import csv
from io import StringIO
from pyspark.sql import SparkSession
import io
connection_string = "AAAA"
container_name = "BBBB"
blob_service_client = BlobServiceClient.from_connection_string(connection_string)
container_client = blob_service_client.get_container_client(container_name)
import gnupg
gpg = gnupg.GPG()
gpg.encoding = 'utf-8'
passphrase = "12345"
secret = "112233"
def decrypt_file(filename, secret, passphrase):
gpg.encoding = 'utf-8'
with open(filename, 'rb') as f:
decrypted_data = gpg.decrypt(f, passphrase=passphrase)
if decrypted_data.ok:
print("done")
else:
print("error:", decrypted_data.status)
print("error:", decrypted_data.stderr)
return str(decrypted_data)
blob_client = container_client.get_blob_client(file)
blob_file_tinb = blob_client.download_blob()
tinb_file = decrypt_file(blob_file_tinb,secret,passphrase)
1 个回答
0
从 Azure Blob 存储中读取一个加密的 CSV 文件,并使用 GnuPG 解密它,然后在 Python 中读取。
你可以使用下面的代码从 Azure Blob 存储中读取这个加密的 CSV 文件,并将其解密,代码是用 Azure 的 Python SDK 写的:
代码:
from azure.storage.blob import BlobServiceClient
import io
import gnupg
connection_string = "xxxxx"
container_name = "logs"
blob_service_client = BlobServiceClient.from_connection_string(connection_string)
container_client = blob_service_client.get_container_client(container_name)
gpg = gnupg.GPG()
gpg.encoding = 'utf-8'
passphrase = "12344"
secret="12344"
def decrypt_file(file, secret, passphrase):
gpg.encoding = 'utf-8'
decrypted_data = gpg.decrypt(file.read(), passphrase=passphrase)
if decrypted_data.ok:
print("done")
else:
print("error:", decrypted_data.status)
print("error:", decrypted_data.stderr)
return str(decrypted_data)
blob_client = container_client.get_blob_client("<filename>")
blob_data = blob_client.download_blob().readall()
tinb_file = decrypt_file(io.BytesIO(blob_data), passphrase, secret)
print(tinb_file)
上面的代码会从 Azure Blob 存储下载一个加密的文件,使用 GnuPG
解密它,并打印出解密后的数据。
代码中设置了 连接字符串
和 容器名称
,然后创建了一个 BlobServiceClient 和 ContainerClient 对象。同时,它还设置了 GnuPG 对象和解密用的密码。最后,它获取了加密文件的 BlobClient 对象,下载文件数据,并将数据传递给 decrypt_file() 函数进行解密和打印。
输出:
done
Industry
Accounting/Finance
Advertising/Public Relations
Aerospace/Aviation
Arts/Entertainment/Publishing
Automotive
Banking/Mortgage
Business Development
Business Opportunity
Clerical/Administrative
Construction/Facilities