0
votes

What is the best way to upload a JSON string (created in memory, not read from a file) to azure blob storage using the python sdk?

I understand from the docs at https://pypi.org/project/azure-storage-blob/ that I can upload a file to azure blob storage by doing the following.

from azure.storage.blob import BlobClient

blob = BlobClient.from_connection_string(conn_str="<connection_string>", container_name="my_container", blob_name="my_blob")

with open("./SampleSource.txt", "rb") as data:
    blob.upload_blob(data)

but I am struggling to find any examples where a string is uploaded directly.

Is it possible to upload a string directly? If so, how is it done in python?

Thanks.

2

2 Answers

4
votes

You can simply pass the string to upload_blob method. No need to do anything special.

For example, code below should work just fine.

blob = BlobClient.from_connection_string(conn_str="<connection_string>", container_name="my_container", blob_name="my_blob")

data = "This is a test"
blob.upload_blob(data)
0
votes

If you're trying to upload a json object and not a json formatted string, you'll first need to turn the json obj into a string so that BlobClient can upload. e.g. if getting a json obj from an api...

response = requests.get("<some endpoint>")
blob = BlobClient.from_connection_string(conn_str="<connection_string>", container_name="my_container", blob_name="my_blob")

data = json.dumps(response.json())
blob.upload_blob(data)