diff --git a/examples/fastapi/app.py b/examples/fastapi/app.py index ee62a37..b216601 100644 --- a/examples/fastapi/app.py +++ b/examples/fastapi/app.py @@ -16,7 +16,6 @@ from sqlalchemy import Column from sqlalchemy_file import File, ImageField from sqlalchemy_file.exceptions import ValidationError -from sqlalchemy_file.processors import ThumbnailGenerator from sqlalchemy_file.storage import StorageManager from sqlalchemy_file.validators import SizeValidator from sqlmodel import Field, Session, SQLModel, create_engine, select @@ -69,8 +68,8 @@ class Category(CategoryBase, table=True): sa_column=Column( ImageField( upload_storage="category", + thumbnail_size=(200, 200), validators=[SizeValidator(max_size="1M")], - processors=[ThumbnailGenerator(thumbnail_size=(200, 200))], ) ) ) diff --git a/examples/flask/__init__.py b/examples/flask/__init__.py index c764a00..e69de29 100644 --- a/examples/flask/__init__.py +++ b/examples/flask/__init__.py @@ -1,125 +0,0 @@ -import os - -from flask import Flask, abort, render_template, request, send_file -from flask_sqlalchemy import SQLAlchemy -from libcloud.storage.drivers.local import LocalStorageDriver -from libcloud.storage.providers import get_driver -from libcloud.storage.types import ( - ContainerAlreadyExistsError, - ObjectDoesNotExistError, - Provider, -) -from sqlalchemy_file import FileField, ImageField -from sqlalchemy_file.exceptions import ValidationError -from sqlalchemy_file.processors import ThumbnailGenerator -from sqlalchemy_file.storage import StorageManager -from sqlalchemy_file.validators import ContentTypeValidator, SizeValidator - -app = Flask(__name__) -app.config[ - "SQLALCHEMY_DATABASE_URI" -] = "sqlite:////tmp/example.db?check_same_thread=False" -db = SQLAlchemy(app, engine_options={"echo": True}) - - -class Book(db.Model): - __tablename__ = "books" - isbn = db.Column(db.Integer, primary_key=True) - author = db.Column(db.String(100), nullable=False) - title = db.Column(db.String(100), nullable=False) - cover = db.Column( - ImageField( - upload_storage="images", - validators=[SizeValidator("16M")], - processors=[ThumbnailGenerator((50, 50))], - ) - ) - document = db.Column( - FileField( - upload_storage="documents", - validators=[ - SizeValidator("5M"), - ContentTypeValidator( - allowed_content_types=[ - "application/pdf", - "application/msword", - "application/vnd.openxmlformats-officedocument.wordprocessingml.document", - ] - ), - ], - ) - ) - - -@app.route("/", methods=("GET", "POST")) -def index(): - error = None - if request.method == "POST": - try: - book = Book( - author=request.form["author"], - title=request.form["title"], - ) - if "cover" in request.files and request.files["cover"].filename != "": - book.cover = request.files["cover"] - if "document" in request.files and request.files["document"].filename != "": - book.document = request.files["document"] - db.session.add(book) - db.session.commit() - except ValidationError as err: - error = err - db.session.rollback() - return render_template( - "index.html", books=Book.query.all(), form=request.form, error=error - ) - - -@app.route("/medias//") -def serve_files(storage, file_id): - try: - file = StorageManager.get_file(f"{storage}/{file_id}") - if isinstance(file.object.driver, LocalStorageDriver): - """If file is stored in local storage, just return a - FileResponse with the fill full path.""" - return send_file( - file.get_cdn_url(), - mimetype=file.content_type, - download_name=file.filename, - ) - elif file.get_cdn_url() is not None: - """If file has public url, redirect to this url""" - return app.redirect(file.get_cdn_url()) - else: - """Otherwise, return a streaming response""" - return app.response_class( - file.object.as_stream(), - mimetype=file.content_type, - headers={"Content-Disposition": f"attachment;filename={file.filename}"}, - ) - except ObjectDoesNotExistError: - abort(404) - - -if __name__ == "__main__": - os.makedirs("/tmp/storage", 0o777, exist_ok=True) - driver = get_driver(Provider.LOCAL)("/tmp/storage") - - # cls = get_driver(Provider.MINIO) - # driver = cls("minioadmin", "minioadmin", secure=False, host="127.0.0.1", port=9000) - - try: - driver.create_container(container_name="images") - except ContainerAlreadyExistsError: - pass - try: - driver.create_container(container_name="documents") - except ContainerAlreadyExistsError: - pass - - StorageManager.add_storage("images", driver.get_container(container_name="images")) - StorageManager.add_storage( - "documents", driver.get_container(container_name="documents") - ) - - db.create_all() - app.run(debug=True) diff --git a/examples/flask/app.py b/examples/flask/app.py new file mode 100644 index 0000000..287171c --- /dev/null +++ b/examples/flask/app.py @@ -0,0 +1,124 @@ +import os + +from flask import Flask, abort, render_template, request, send_file +from flask_sqlalchemy import SQLAlchemy +from libcloud.storage.drivers.local import LocalStorageDriver +from libcloud.storage.providers import get_driver +from libcloud.storage.types import ( + ContainerAlreadyExistsError, + ObjectDoesNotExistError, + Provider, +) +from sqlalchemy_file import FileField, ImageField +from sqlalchemy_file.exceptions import ValidationError +from sqlalchemy_file.storage import StorageManager +from sqlalchemy_file.validators import ContentTypeValidator, SizeValidator + +app = Flask(__name__) +app.config[ + "SQLALCHEMY_DATABASE_URI" +] = "sqlite:////tmp/example.db?check_same_thread=False" +db = SQLAlchemy(app, engine_options={"echo": True}) + + +class Book(db.Model): + __tablename__ = "books" + isbn = db.Column(db.Integer, primary_key=True) + author = db.Column(db.String(100), nullable=False) + title = db.Column(db.String(100), nullable=False) + cover = db.Column( + ImageField( + upload_storage="images", + thumbnail_size=(50, 50), + validators=[SizeValidator("16M")], + ) + ) + document = db.Column( + FileField( + upload_storage="documents", + validators=[ + SizeValidator("5M"), + ContentTypeValidator( + allowed_content_types=[ + "application/pdf", + "application/msword", + "application/vnd.openxmlformats-officedocument.wordprocessingml.document", + ] + ), + ], + ) + ) + + +@app.route("/", methods=("GET", "POST")) +def index(): + error = None + if request.method == "POST": + try: + book = Book( + author=request.form["author"], + title=request.form["title"], + ) + if "cover" in request.files and request.files["cover"].filename != "": + book.cover = request.files["cover"] + if "document" in request.files and request.files["document"].filename != "": + book.document = request.files["document"] + db.session.add(book) + db.session.commit() + except ValidationError as err: + error = err + db.session.rollback() + return render_template( + "index.html", books=Book.query.all(), form=request.form, error=error + ) + + +@app.route("/medias//") +def serve_files(storage, file_id): + try: + file = StorageManager.get_file(f"{storage}/{file_id}") + if isinstance(file.object.driver, LocalStorageDriver): + """If file is stored in local storage, just return a + FileResponse with the fill full path.""" + return send_file( + file.get_cdn_url(), + mimetype=file.content_type, + download_name=file.filename, + ) + elif file.get_cdn_url() is not None: + """If file has public url, redirect to this url""" + return app.redirect(file.get_cdn_url()) + else: + """Otherwise, return a streaming response""" + return app.response_class( + file.object.as_stream(), + mimetype=file.content_type, + headers={"Content-Disposition": f"attachment;filename={file.filename}"}, + ) + except ObjectDoesNotExistError: + abort(404) + + +if __name__ == "__main__": + os.makedirs("/tmp/storage", 0o777, exist_ok=True) + driver = get_driver(Provider.LOCAL)("/tmp/storage") + + # cls = get_driver(Provider.MINIO) + # driver = cls("minioadmin", "minioadmin", secure=False, host="127.0.0.1", port=9000) + + try: + driver.create_container(container_name="images") + except ContainerAlreadyExistsError: + pass + try: + driver.create_container(container_name="documents") + except ContainerAlreadyExistsError: + pass + + StorageManager.add_storage("images", driver.get_container(container_name="images")) + StorageManager.add_storage( + "documents", driver.get_container(container_name="documents") + ) + + db.create_all() + app.run(debug=True) diff --git a/mkdocs.yml b/mkdocs.yml index 05876b0..160279a 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -69,7 +69,7 @@ watch: extra: analytics: provider: google - property: G-6GVDGPXNYF + property: G-DX31D2F61K social: - icon: fontawesome/brands/github link: https://github.com/jowilf