将文件保存到 Azure Blob [英] Saving file into Azure Blob

查看:34
本文介绍了将文件保存到 Azure Blob的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用下面的 python 代码将文件保存到本地文件夹中.我想直接将此文件保存到 Azure Blob 中.我不希望文件存储在本地然后上传到 blob.

I am using below python code to save the file into local folder. I want to save this file into Azure Blob directly. I do not want file to be stored locally and then upload into blob.

我尝试在文件夹变量中提供 blob 位置,但没有奏效.我有想要从 Web 浏览器读取并使用 python 保存到 Azure blob 中的 excel 文件.

I tried giving blob location in folder variable but it did not work. I have excel file that I want to read from Web browser and saved into Azure blobs using python.

 folder = 'Desktop/files/ab'
    
 r = requests.get(api_end_point, headers=api_headers, stream=True)
 with open(folder, 'wb') as f:
    f.write(r.content)

推荐答案

首先你应该将文件作为类似流的东西.

First you should get the files as something like stream.

import os
from azure.storage.blob import BlobServiceClient, BlobClient, ContainerClient


connect_str = os.getenv('str')
blob_service_client = BlobServiceClient.from_connection_string(connect_str)
container_name = "test"
container_client = blob_service_client.get_container_client(container_name)
blob_client = blob_service_client.get_blob_client(container_name, "MyFirstBlob.txt")
blob_client.upload_blob(req.get_body(), blob_type="BlockBlob")

在我这边,我将数据放在请求正文中,然后将其上传到 azure blob.是流.你也可以在里面放一个流.

On my side, I put the data in the body of request, and I upload that to azure blob. It is stream. You can also put a stream in it.

这些是官方文档:

https://docs.microsoft.com/en-us/azure/storage/blobs/storage-quickstart-blobs-python#upload-blobs-to-a-container

https://docs.microsoft.com/en-us/azure/developer/python/sdk/storage/azure-storage-blob/azure.storage.blob.blobserviceclient?view=storage-py-v12

https://docs.microsoft.com/en-us/azure/developer/python/sdk/storage/azure-storage-blob/azure.storage.blob.blobclient?view=storage-py-v12#upload-blob-data--blob-type--blobtype-blockblob---blockblob----length-none--metadata-none----kwargs-

这篇关于将文件保存到 Azure Blob的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆