1

I want some files (images in this case) in a private bucket on Backblaze to be exposed by an API endpoint in Flask. I'm not sure how to handle the DownloadedFile object that is returned from bucket.download_file_by_name

@app.route('/b2-image/<filename>', methods=('GET',))
def b2_image(filename):
    info = InMemoryAccountInfo()
    b2_api = B2Api(info)
    app_key_id = env['MY_KEY_ID']
    app_key = env['MY_KEY']

    b2_api.authorize_account('production', app_key_id, app_key)
    bucket = b2_api.get_bucket_by_name(env['MY_BUCKET'])

    file = bucket.download_file_by_name(filename)

    bytes = BytesIO()

    #something sort of like this??? 
    #return Response(bytes.read(file), mimetype='image/jpeg')
    

bucket.download_file_by_name returns a DownloadedFile object, I'm not sure how to handle it. The documentation provides no examples and seems to suggest I'm supposed to do something like:

file = bucket.download_file_by_name(filename)

#this obviously doesn't make any sense
image_file = file.save(file, file)
pspahn
  • 2,770
  • 4
  • 40
  • 60
  • Full disclosure - I'm a developer evangelist at Backblaze. I'm curious - is there a reason you're using the B2 Native API rather than the S3 Compatible API? – metadaddy Feb 10 '22 at 19:46
  • 1
    @metadaddy No I don't suppose there is. I am working with a Django project and was looking at `django-backblaze` module and it didn't quite meet my needs. I saw it using the Python SDK so I started using the Python SDK and decided to put the file storage on a different layer in Flask instead of Django directly. – pspahn Feb 12 '22 at 00:16
  • The S3 Django storages backend works just fine with B2 - no extra code, just config. See my Reddit comment: https://www.reddit.com/r/backblaze/comments/sdb2m7/django_with_backblaze/hud0r20/?utm_source=reddit&utm_medium=web2x&context=3 – metadaddy Feb 13 '22 at 23:32

1 Answers1

1

I had been trying the following but it wasn't working:

file = bucket.download_file_by_name(filename)
f = BytesIO()
file.save(f)

return Response(f.read(), mimetype='image/jpeg')

This SO Answer gave me the clue I needed, specifically setting the seek value on the BytesIO object:

#this works
file = bucket.download_file_by_name(filename)
f = BytesIO()
file.save(f)
f.seek(0)

return Response(f.read(), mimetype='image/jpeg')
pspahn
  • 2,770
  • 4
  • 40
  • 60
  • Glad you got it working! Could you 'check' your answer so it's easier to see that it solved the problem? – metadaddy Feb 26 '22 at 18:17