3
votes

I created some models using SqlAlchemy for setting up the database initially. Initially i parse some XML files and populate the database. This is a one time thing which needs to be done when i setup the app on server.

Base = declarative_base()

class Movie(Base):
        __tablename__ = 'Movies'
        id = Column(Integer, primary_key=True, autoincrement=True)
        title = Column(String(80))
        filename = Column(String(80), unique=True)
        genre = Column(String(80))
        language = Column(String(80))
        year = Column(Integer)
        description = Column(Text)
        poster = Column(String)

        def __init__(self, title, filename, genre, language, year, description, poster):
            self.title = title
            self.filename = filename
            self.genre = genre
            self.language = language
            self.year = year
            self.description = description
            self.poster = poster

        def __repr__(self):
            return '<Movie (id=%d, title=%s, filename=%s, genre=%s, year=%s, description=%s, poster=%s)>' % (
                self.id, self.title, self.filename, self.genre, self.year, self.description, self.poster )
......

Now i want to use the same models in the flask also for a REST api. But from what i have seen, first i need to create a db instance using the flask app - like this

app = Flask(__name__)
db = SQLAlchemy(app)
class Movie(db.Model):
.......

How does this workout? Since my models are inheriting from the Base class but for flask they need to inherit from the db.Model class.

2
Doesn't matter. The db.Model is just a proxy class for Base. You can do exactly what you have.nathancahill
Does this answer your question? Using SQLAlchemy models in and out of FlaskJoe
I found a nice solution: stackoverflow.com/a/64668814/7919597Joe

2 Answers

1
votes

you can simply use your models as they are, they do not "need" to inherit from db.Model, that is simply a convince to make flask integration easier

1
votes

You can to create a module with the SQLAlchemy instance and use only the inheritance in the another's modules.

in database.py module:

from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()

movieModel.py

from database import db

class MovieModel(db.Model):
    __tablename__ = 'movie'

    id = db.Column(db.Integer, primary_key=True)

imageModel.py

from database import db

class ImageModel(db.Model):
    __tablename__ = 'image'

    id = db.Column(db.Integer, primary_key=True)