打开Azure StorageStreamDownloader而不将其另存为文件


问题内容

我需要从azure的blob容器中下载PDF作为下载流(StorageStreamDownloader),并在PDFPlumber和PDFminer中将其打开。我开发了将它们作为文件加载的所有要求,但是我无法设法接收到下载流(StorageStreamDownloader)并成功打开它。我正在打开这样的PDF:

pdf = pdfplumber.open(pdfpath) //for pdfplumber
fp = open('Pdf/' + fileGlob, 'rb')  // for pdfminer
parser = PDFParser(fp) 
document = PDFDocument(parser)

但是,我需要能够下载流。将pdf下载为文件的代码段:

blob_client = container.get_blob_client(remote_file)
with open(local_file_path,"wb") as local_file:
    download_stream = blob_client.download_blob()
    local_file.write(download_stream.readall())
    local_file.close()

我尝试了几种选择,甚至使用没有运气的临时文件。有任何想法吗?


问题答案:

download_blob()将blob下载到一个StorageStreamDownloader
类中,并且在该类中有个download_to_stream,您将获得blob流。

from azure.storage.blob import BlobServiceClient, BlobClient, ContainerClient
from io import BytesIO
import PyPDF2
filename = "test.pdf"

container_name="test"

blob_service_client = BlobServiceClient.from_connection_string("connection string")
container_client=blob_service_client.get_container_client(container_name)
blob_client = container_client.get_blob_client(filename)
streamdownloader=blob_client.download_blob()

stream = BytesIO()
streamdownloader.download_to_stream(stream)

fileReader = PyPDF2.PdfFileReader(stream)

print(fileReader.numPages)

这就是我的结果。它将打印pdf页码。

在此处输入图片说明