'Where should I close it file? [closed]

def get_pic(f_id: str):
    __file__ = open(db_files.get_pic(f_id), mode='rb')
    return StreamingResponse(__file__, media_type="image/jpg")

if i file.close() cant return if i return cant close Where should I close it file?



Solution 1:[1]

def iterfile():
    with open(db_files.get_pic(f_id), "rb") as img:
        yield from img
return StreamingResponse(iterfile(), media_type="image/jpg")

Solution 2:[2]

You should use with open...:

def get_pic(f_id: str):
    with open(db_files.get_pic(f_id), mode='rb') as __file__:
        img_to_return = StreamingResponse(__file__, media_type="image/jpg")
    return img_to_return

This implicitly calls __file__.close()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 IFCZT
Solution 2