Skip to main content

File-Alchemy

Python version PyPi version
At the moment, the library can only work correctly on the Flask framework platform.

Quick start

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from file_alchemy import FileManager, Base64ImageAttach

app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///project.db"
app.config['UPLOAD_FOLDER'] = 'UPLOAD_FOLDER'
db = SQLAlchemy(app)
filemanager = FileManager(app, db)


class User(db.Model):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    email = Column(String, unique=True, nullable=False)
    phone_number = Column(String, unique=True)
    username = Column(String, unique=True, nullable=False)
    password = Column(String, nullable=False)
    avatar = Column(String, nullable=True) # Column will store path to image file

# Register file attachment 
"""
    Path generated:
 {app.config["UPLOAD_FOLDER"]}/{Base64ImageAttach.__name__}/{Model.__tablename__}/{prefix}
"""
avatar_file = filemanager.attach_field(
    Base64ImageAttach(
        column=User.avatar, # attached column *Required
        filename_generator=User.username, # file name generator column must be unique! *Required
        prefix='/avatars', # prefix in file path must be unique for table *Required
        size=(400, 400) # image size width x height *Optional
    )
)
""" 
    Base64ImageAttach responsible for adding, deleting, updating the image and its title, while inserting, deleteing, updating rows in table.
    Base64ImageAttach is waiting base64 image format to set in attached column - https://en.wikipedia.org/wiki/Base64 
"""

with app.app_context():
    db.drop_all()
    db.create_all()

# Get uploaded files
from flask import send_from_directory

@app.get('UPLOAD_FOLDER/<path>')
def get_files(path):
    return send_from_directory(filemanager.upload_folder or app.config['UPLOAD_FOLDER'], path=path)

# create user
import base64


def create_user(app):
    """
        Create user with avatar from base64 encoded image
    """
    with app.app_context() as app:
        with open('tests/test.jpg', 'rb') as file:
            base64_image = str(base64.b64encode(file.read()), encoding='utf-8')
        user = User(
            email='email@gmail.com',
            username='username',
            avatar=base64_image,
        )
        db.session.add(user)
        db.session.commit()

create_user(app)

User model

idemailusernameavatar
1email@gmail.comusernameUPLOAD_FOLDER/images/users/avatars/username.jpg

Attention!

# DONT use this statement to update attached model's instance
db.session.query(Model).filter("condition").update(data)
# It doesn't trigger file attacher
# you can use this instead
for key, value in data.items():
    setattr(instance, key, value)

Metadata

Release files for file-alchemy 0.0.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for file-alchemy 0.0.1
File Size Uploaded
file-alchemy-0.0.1.tar.gz 9.6 kB Details

Release files / file-alchemy-0.0.1.tar.gz

Download URL file-alchemy-0.0.1.tar.gz
Size 9.6 kB
Tags Source
SHA-256 checksum
How to use checksums
a28533e3d13f8be2852fd06a96843acd930292dd4625c0689d5c10671eca9b67
BLAKE2b-256 checksum
How to use checksums
768c6ddef2e263c46cc2c529b453b1e09423b0d4364dc0a330f4033af46a5f0a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/4.0.1 CPython/3.10.0

Release history Release notifications | RSS feed

This release

0.0.1 This release

1 release file

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page