New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Can't detect models.py schema #50
Comments
Hi @jeffjzx. The problem is that
I'm surprised you are not getting a circular reference issue with your code. |
I have the exact same problem with the pattern, but even with the design from the last comment my generated migration script comes out empty: from flask import Flask
from flask.ext.migrate import Migrate, MigrateCommand
from flask.ext.script import Manager
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config.from_object('myapp.webservice.config')
if 'MYAPP_SERVICE_SETTINGS' in os.environ:
app.config.from_envvar('MYAPP_SERVICE_SETTINGS')
db = SQLAlchemy(app)
import myapp.webservice.models
migrate = Migrate(app, db)
cli_manager = Manager(app)
cli_manager.add_command('db', MigrateCommand)
if __name__ == '__main__':
cli_manager.run() The generated migration script looks like this: """empty message
Revision ID: 7ba986fc62
Revises: None
Create Date: 2015-04-26 12:00:31.400071
"""
# revision identifiers, used by Alembic.
revision = '7ba986fc62'
down_revision = None
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - please adjust! ###
pass
### end Alembic commands ###
def downgrade():
### commands auto generated by Alembic - please adjust! ###
pass
### end Alembic commands ### |
@jbaiter: any chance you have a database that already has the tables in it? If that's the case, then Alembic is not going to find any difference between your models and the database. Try dropping all the tables in your database. |
@miguelgrinberg, no, the table was empty. I managed to solve it now, though, through some restructuring of my code. The problem in my case was that the initialization code was located in the package's |
In my case I was not using flask-sqlalchemy, just plain alchemy. (My models were subclass of Base). |
I used this to recursively import all models. # manager.py
import importlib
import os
from app import manager
MODELS_DIRECTORY = "models"
EXCLUDE_FILES = ["__init__.py"]
def import_models():
for dir_path, dir_names, file_names in os.walk(MODELS_DIRECTORY):
for file_name in file_names:
if file_name.endswith("py") and not file_name in EXCLUDE_FILES:
file_path_wo_ext, _ = os.path.splitext((os.path.join(dir_path, file_name)))
module_name = file_path_wo_ext.replace(os.sep, ".")
importlib.import_module(module_name)
if __name__ == '__main__':
import_models()
manager.run() |
@beebek , your |
I have modified your version slightly to use with large applications with blueprints and all. Putting the following code in a top level source and calling the
This also assumes that you have installed your application as development mode or actually installed it as distribution. |
Hi Miguel, About the original issue with the circular import, after I create db with |
@mchensd can't really tell you without seeing the code and the stack trace of the error. Can you provide that? |
In my main file, app.py:
In models.py:
When I try to perform migrations, I get this:
Meaning there is still a circular import. |
@mchensd is
The easy solution is to replace |
It works now! Kind of trivial, but in |
I think this is a bug in the IDE's linter, but it is a very common one. Do you have a way to add exceptions in your IDE? For example, flake8 and pylint both allow you to tell the linter to ignore certain errors by adding a comment on the offending line. Not sure what else you can do if the IDE does not have a bypass option. You may also consider not having |
Ok, thanks for the help! |
This issue will be automatically closed due to being inactive for more than six months. Seeing that I haven't responded to your last comment, it is quite possible that I have dropped the ball on this issue and I apologize about that. If that is the case, do not take the closing of the issue personally as it is an automated process doing it, just reopen it and I'll get back to you. |
@beebek IMHO, this structure is more beautiful to solve a problem with imports of models, we avoide of the circle import and we follow PEP 8 as well. # Hook up models.
from app import models
from flask import Blueprint, render_template
from app.models import User
app_bp = Blueprint('app', __name__)
@app_bp.route('/')
def home():
users = User.query.all()
return render_template('app/home.html', users=users)
from core import db
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(64), index=True, unique=True)
email = db.Column(db.String(120), index=True, unique=True)
password_hash = db.Column(db.String(128))
def __repr__(self):
return '<User {}>'.format(self.username)
import os
from flask import abort, Flask, g
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
try:
from core import local_settings as settings
except ImportError:
from core import settings
__version__ = '1.0.0'
babel = Babel()
db = SQLAlchemy()
migration = Migrate()
def create_app() -> Flask:
"""
Creates application with predefined settings that depends on
environment variable of a system.
"""
application = Flask(
__name__,
template_folder=settings.TEMPLATE_DIR,
static_folder=settings.STATIC_DIR
)
# Load configuration.
environment = os.environ.get('APP_ENV', 'dev')
environments = {
'dev': settings.Dev,
'prod': settings.Prod
}
application.config.from_object(environments[environment])
# Initialize third-party libs.
babel.init_app(application)
db.init_app(application)
migration.init_app(application, db)
# Register blueprints
from app.views import app_bp
application.register_blueprint(app_bp)
return application |
Hi, miguelgrinberg:
I'm trying out this library along with instruction, in the following style of code i have put all the code in one file:
And when i type "python app.py db init" and "python app.py db migrate", the migration script is generated just fine.
Then i delete .db file and "migrations" folder and want to try this in the following setting:
i put all the database model definition in the file "models.py" which is at the same level with "app.py"
And in "app.py"
And after initialization and "python app.py db migrate", the migration script shows:
Which means flask-migrate doesn't detect database model definition in this type of code layout.
I'm not sure why this is the case, definitely somewhere has been messed up, but i'm not sure where is it.
Thanks in advance
The text was updated successfully, but these errors were encountered: