2

I am working on a project using Flask and SqlAlchemy. Me and my colleagues found two ways to define a table. Both work, but what is the different?

Possibility I

base = declarative_base()

class Story(base):
        __tablename__ = 'stories'
        user_id = Column(Integer, primary_key=True) 
        email = Column(String(100), unique=True)
        password = Column(String(100), unique=True)

Possibility II

db = SQLAlchemy()

class Story(db.Model):
        __tablename__ = 'stories'
        user_id = db.Column(Integer, primary_key=True) 
        email = db.Column(String(100), unique=True)
        password = db.Column(String(100), unique=True)

We want to choose one option, but which one? It is obvious that both classes inherit from a different parent class, but for what are these two possibilities used for?

1
  • use default base and using custom base and DRY each time Commented Jan 23, 2023 at 10:27

1 Answer 1

2

Possibility 1 is raw SQLAlchemy declarative mapping.

Possibility 2 is Flask-SQLAlchemy.

Both map a class to SQL table (or something more exotic in SQL) in a declarative style, i.e. the class is mapped to an automatically generated table.

Choosing which one to use however is a matter of opinion.

I'll say that using Flask-SQLAlchemy is obviously locking the application to Flask, but that's basically a non-problem since switching frameworks is very uncommon.

NB. __tablename__ is optional with Flask-SQLAlchemy.

Sign up to request clarification or add additional context in comments.

1 Comment

I agree with this answer. For addition, in agile architecture no. 1 is better. In terms of agility, dependency, flexibility and performance (flask-sqlalchemy somehow make it worst). But if you're a beginner, flask-sqlalchemy provide you some features to easily manage your queries.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.