1

I'm using firebase to upload images using python and pyrebase, the post request is:

@router.post('/', response_model=schemas.Product)
def add_product(
            file: UploadFile = File(),
            db: Session = Depends(get_db)
            ):
try:
    firebase = pyrebase.initialize_app(settings.config_firebase)
    storage = firebase.storage()
    path_on_cloud = "products/"+file.filename
    photo_infos = storage.child(path_on_cloud).put(file.file)
    print(firebase)  # op 1
    print(storage)   # op 2
    print(path_on_cloud)   # op 3
    print(photo_infos)   # op 4

first output (op1)

<pyrebase.pyrebase.Firebase object at 0x000001889A691790>

which means that the connection works fine

2nd:

<pyrebase.pyrebase.Storage object at 0x000001889A76A8B0>

3rd

products/baqlawa.png

4th: and here is the problem

None

the storage rules in firebase are:

rules_version = '2';
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
  allow read, write: if false;
    }
  }
}

Note: the reading request of files works fine, the problem is in uploading, and I did not using any authentication requirement.

Other thing I want to add is that in firebase console the files are added but as application/octet-stream and not jpeg or png

thank you in advance.

  • Are you reading the file contents before passing the file obj to `.put()`? If so, use `file.file.seek(0)` to rewind the cursor to the start of the file, as described in [this answer](https://stackoverflow.com/a/70653605/17865804) and [this answer](https://stackoverflow.com/a/71052898/17865804). Also, the `.put()` method might take the path to a local file, and not a file object. In that case, you might need to use a `NamedTemporaryFile`, as described in the linked answer above. – Chris Sep 18 '22 at 07:32
  • UploadFile in fastapi uses SpooledTemporaryFile object, I tried solutions u said and it does not work. the files in firebase are uploaded but as application/octet-stream and not jpeg or png – Younes Khellaf Sep 19 '22 at 06:36
  • 1
    Thank u, It works by keep the bytes in an in-memory buffer BytesIO (like you said in an other question as 3rd option) – Younes Khellaf Sep 20 '22 at 19:04
  • It excepts an error: total bytes could not be determined. Please pass an explicit size, or supply a chunk size for a streaming transfer – Younes Khellaf Sep 21 '22 at 13:33
  • please, can you tell me wich method is preferable to use for my app wich will be deployed as a servless app in aws – Younes Khellaf Sep 21 '22 at 13:38
  • update: sorry, but it works using aiofiles (like the second answer u tell me about in your first comment) – Younes Khellaf Sep 21 '22 at 14:33

1 Answers1

0

go to the storage rules in firebase and .....just change false into true.