SQLAlchemy extension isn't registered when run

2019-06-18 03:06发布

I have an application that works in development, but when I try to run it with Gunicorn it gives an error that the "sqlalchemy extension was not registered". From what I've read it seems that I need to call app.app_context() somewhere, but I'm not sure where. How do I fix this error?

# run in development, works
python server.py

# try to run with gunicorn, fails
gunicorn --bind localhost:8000 server:app

AssertionError: The sqlalchemy extension was not registered to the current application.  Please make sure to call init_app() first.

server.py:

from flask.ext.security import Security
from database import db
from application import app
from models import Studio, user_datastore

security = Security(app, user_datastore)

if __name__ == '__main__':
    # with app.app_context(): ??
    db.init_app(app)
    app.run()

application.py:

from flask import Flask

app = Flask(__name__)
app.config.from_object('config.ProductionConfig')

database.py:

from flask.ext.sqlalchemy import SQLAlchemy
db = SQLAlchemy()

1条回答
霸刀☆藐视天下
2楼-- · 2019-06-18 03:36

Only when you start your app with python sever.py is the if __name__ == '__main__': block hit, where you're registering your database with your app.

You'll need to move that line, db.init_app(app), outside that block.

查看更多
登录 后发表回答