I'm having a hard time to make my application run. Flask-SQLAlchemy extension creates an empty database whenever I try to separate module in packages. To better explain what I'm doing, let me show how my project is structured:
Project
|
|-- Model
| |-- __init__.py
| |-- User.py
|
|-- Server
| |-- __init__.py
|
|-- API
| |-- __init__.py
The idea is simple: I want to create a package for my model, as I don't like spreading code in a single package, and separate "sub" projects (like API), as in the future I will be using blueprints to better isolate sub apps.
The code is very simple:
First, the Model.__init__.py
:
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
Note that I created this only to use a single SQLAlchemy()
object accross the package. No we go to Model.User
from Model import db
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
Name = db.Column(db.String(80))
Age = db.Column(db.Integer)
...
Once again note the from Model import db that I used to allow the same db object.
Finally, the Server.__init__.py
goes like this:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
import Model, API
db = Model.db
def main():
app = Flask("__main__")
db = SQLAlchemy(app)
db.create_all()
API.SetAPIHookers(app)
app.run(host="0.0.0.0", port=5000, debug=True)
if __name__ == "__main__":
main()
From my point of view, the db = SQLAlchemy(app)
allows me to pass my app object without creating a circular reference.
The problem is that whenever I run this code, the sqlite database file is created empty. That made me think that maybe Python don't import things like I thought it would. So I tested my theory by removing the import Model and creating the user directly inside Server... and voilá, it worked!
Now comes my question: Is there a 'pythonic' way to correctly separate modules like I want or should I leave everything in the same package?
See Question&Answers more detail:
os