Install & Compatibility
Where this runs
No compatibility data collected yet for this library.
Code
Verified usage
Verified import paths — ran on the pinned version, not inferred.
File
✓ from sqlalchemy_file import File
✗ from sqlalchemy_file import File as OldFile
Old import paths from pre-0.5.0 may exist; use this.
ImageField
✓ from sqlalchemy_file import ImageField
✗ from sqlalchemy_file.fields import ImageField
ImageField is directly importable from the main module since v0.5.0.
Basic usage: define a model with a FileField column, attach files via Attach object.
from sqlalchemy import create_engine, Column, Integer
from sqlalchemy.orm import declarative_base
from sqlalchemy_file import File, FileField
Base = declarative_base()
engine = create_engine('sqlite:///:memory:')
class User(Base):
__tablename__ = 'user'
id = Column(Integer, primary_key=True)
avatar = Column(FileField)
Base.metadata.create_all(engine)
from sqlalchemy.orm import Session
from sqlalchemy_file import Attach
with Session(engine) as session:
user = User()
user.avatar = Attach('path/to/avatar.jpg', content_type='image/jpeg')
session.add(user)
session.commit()
print(user.avatar.url)
Errors
Common errors & fixes
AttributeError: 'File' object has no attribute 'url'
Accessing url on a File instance before attaching to a model or after deletion.
fixEnsure the file is attached to a model instance and committed. Use user.avatar.url after session.commit().
sqlalchemy.exc.CompileError: Can't generate DDL for Column type FileField; is it a mapped column?
Using FileField without proper SQLAlchemy column declaration or missing SQLAlchemy-file extension.
fixDeclare the column as Column(FileField) and ensure the model inherits from declarative_base.
ImportError: cannot import name 'FileField' from 'sqlalchemy_file'
Outdated version of sqlalchemy-file (<0.5.0) where FileField was not exported from top-level.
fixUpgrade to >=0.5.0: pip install --upgrade sqlalchemy-file.
Upgrade
Version history
0.6.0latest on PyPI · released Oct 7, 2023
Audit
Dependencies
sqlalchemyrequiredRequired: core ORM dependency
boto3optionalRequired for S3 storage backend
google-cloud-storageoptionalRequired for GCS storage backend