6

I want to stream data to azure block blob with python. The code below creates the blob but ends up with zero bytes. How can I make this work?

import io
import struct
from azure.storage.blob import BlockBlobService

storage = BlockBlobService('acct-xxx', 'key-xxx')
stream = io.BytesIO()
storage.create_blob_from_stream("mycontainer", "myblob", stream)
stream.write(struct.pack("d", 12.34))
stream.write(struct.pack("d", 56.78))
stream.close()
2
  • Hi,Greg. Any progress? Commented Sep 25, 2017 at 7:27
  • I don't think the python library will serve my needs. Commented Sep 26, 2017 at 14:14

2 Answers 2

3

It seems that you've missed the key line of code:

stream.seek(0)

I set the stream's Position property to 0 then your code works.

import io
import struct
from azure.storage.blob import BlockBlobService

storage = BlockBlobService('acct-xxx', 'key-xxx')
stream = io.BytesIO()

stream.write(struct.pack("d", 12.34))
stream.write(struct.pack("d", 56.78))
stream.seek(0)
storage.create_blob_from_stream("mycontainer", "myblob", stream)
stream.close()

enter image description here

You could refer to this thread Azure storage: Uploaded files with size zero bytes.

Sign up to request clarification or add additional context in comments.

3 Comments

This would require holding the entire stream in memory. I want to stream data as I get it without incurring a large memory footprint.
@GregClinton Hi,Greg. storage.create_blob_from_stream is a http request package for rest API actually, it's a synchronous blocking mode so you can't operate stream that has been uploaded to azure.
This one is a life saver. I had seeked to the end to find the size of a flask file and forgot to seek back! Thanks.
2

I recommend using smart_open.

from smart_open import open

# stream from Azure Blob Storage
with open('azure://my_container/my_file.txt') as fin:
    for line in fin:
        print(line)

# stream content *into* Azure Blob Storage (write mode):
with open('azure://my_container/my_file.txt', 'wb') as fout:
    fout.write(b'hello world')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.