我正在尝试按照此处的官方文档(https://learn.microsoft.com/en-us/azure/storage/blobs/storage-blob-upload-python)将文件上传到Azure。
我得到了 URL 和 SAS_TOKEN,但自己没有登录 Azure 来检查。
我更喜欢以同步方式上传,但已安装的库需要等待一些东西。 官方文档似乎是错误的,例如在无类函数中需要 self 参数。
我目前将我的秘密保存在 settings.py 文件中。
import asyncio
import os
from azure.identity.aio import DefaultAzureCredential
from azure.storage.blob.aio import BlobServiceClient, BlobClient, ContainerClient
from settings import ACCOUNT_NAME, SAS_TOKEN, AZURE_CONTAINER_NAME
from pathlib import Path
def get_blob_service_client_sas(sas_token: str = SAS_TOKEN):
account_url = f"https://{ACCOUNT_NAME}.blob.core.windows.net"
blob_service_client = BlobServiceClient(account_url, credential=sas_token)
return blob_service_client
def upload_blob_file(blob_service_client: BlobServiceClient, container_name: str = AZURE_CONTAINER_NAME):
container_client = blob_service_client.get_container_client(container=container_name)
data = Path('demo.png').read_bytes()
container_client.upload_blob(name="demo.png", data=data, overwrite=True)
# Define another async function that calls the first one
async def main():
bsc = get_blob_service_client_sas()
print(bsc)
await upload_blob_file(blob_service_client=bsc)
# Run the async function from a synchronous context
asyncio.run(main())
此代码崩溃了
TypeError: object NoneType can't be used in 'await' expression
我很感激任何关于如何上传文件的工作示例 - 即使它是基于curl代码、请求或httpx。
上传(然后下载)。真实世界的文件大小为 5 GB,但目前我正在使用一个小文件进行测试。
要将小文件上传到Azure Blob存储,您可以使用下面的代码。
代码:
from azure.storage.blob import BlobServiceClient
Account_name="venkat789"
sas_token="<sas-token>"
container_name="test"
account_url = f"https://{Account_name}.blob.core.windows.net"
blob_service_client = BlobServiceClient(account_url, credential=sas_token)
container_client = blob_service_client.get_container_client(container=container_name)
local_path = r"C:\users\bike.png"
blob_name = "example.png"
blob_client = container_client.get_blob_client(blob_name)
with open(local_path, "rb") as data:
blob_client.upload_blob(data)
输出:
对于较大的文件上传,您可以使用我的这个SO-thread。