I\'m trying to figure out how to have SQLAlchemy classes spread across several files, and I can for my life not figure out how to do it. I am pretty new to SQLAlchemy so for
For me, adding import app.tool.tool_entity
inside app.py
and from app.tool.tool_entity import Tool
inside tool/__init__.py
was enough to get the table to be created. I haven't tried adding relationship yet, though.
Folder structure:
app/
app.py
tool/
__init__.py
tool_entity.py
tool_routes.py
# app/tool/tool_entity.py
from app.base import Base
from sqlalchemy import Column, Integer, String
class Tool(Base):
__tablename__ = 'tool'
id = Column(Integer, primary_key=True)
name = Column(String, nullable=False)
fullname = Column(String)
fullname2 = Column(String)
nickname = Column(String)
def __repr__(self):
return "" % (
self.name, self.fullname, self.nickname)
# app/tool/__init__.py
from app.tool.tool_entity import Tool
# app/app.py
from flask import Flask
from sqlalchemy import create_engine
from app.tool.tool_routes import tool_blueprint
from app.base import Base
db_dialect = 'postgresql'
db_user = 'postgres'
db_pwd = 'postgrespwd'
db_host = 'db'
db_name = 'db_name'
engine = create_engine(f'{db_dialect}://{db_user}:{db_pwd}@{db_host}/{db_name}', echo=True)
Base.metadata.create_all(engine)
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'hello world'
app.register_blueprint(tool_blueprint, url_prefix='/tool')
if __name__ == '__main__':
# you can add this import here, or anywhere else in the file, as debug (watch mode) is on,
# the table should be created as soon as you save this file.
import app.tool.tool_entity
app.run(host='0.0.0.0', port=5000, debug=True)