masonCherry
masonCherry

Reputation: 974

How does Flask_SQLAlchemy know which Models Classes you've defined

I'm using flask with flask_sqlalchemy and I'm a bit perplexed.

This code runs but when you run db.create_all() the database you get is empty with not tables.

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
db = SQLAlchemy(app)
db.create_all()

class Urls(db.Model):
    id = db.Column(db.Integer, primary_key=True)  # autoincrement=True)
    name = db.Column(db.String(100), unique=True, nullable=False)
    title = db.Column(db.String(100))
    zone = db.Column(db.Integer, default=10, nullable=False)

The fix is to push the definition of the Users class above the db.create_all() line. Then you get a database with the users table inside it.

My Question is how can db.create_all() know that the Users class is now defined. is create_all somehow importing the file again?

Furthermore how does it know to use Urls and not any other class. This seems like black magic to me.

Upvotes: 0

Views: 86

Answers (1)

Dave W. Smith
Dave W. Smith

Reputation: 24966

If you approach this by finding and reading the flask_sqlalchemy source, it might well appear to be black magic. That's not easy code to follow for someone new to Python. The sqlalchemy source is even deeper magic.

A somewhat simpler question is to answer is how a given class can locate its subclasses. For that, Python classes have a special __subclasses__ method that returns a list of (weak) references to immediate subclasses. With that and a bit of extra work, it's possible to walk a tree of subclasses.

For example, if Bar is a subclass of Foo:

>>> class Foo: pass
... 
>>> class Bar(Foo): pass
... 
>>> Foo.__subclasses__()
[<class '__main__.Bar'>]

See https://docs.python.org/3/library/stdtypes.html near the bottom.

Upvotes: 1

Related Questions