0

I have a module which I want to use for handling database access to both the production and a test database.

The content looks like this:

class FirstModel(db.Model):
    #...
class SecondModel(db.Model):
    #...

def get_production_connection():
    app = Flask(__name__)
    app.config['SQLALCHEMY_DATABASE_URI'] = PRODUCTION_DATABASE_URI
    db = SQLAlchemy(app)
    return db

def get_test_connection():
    app = Flask(__name__)
    app.config['SQLALCHEMY_DATABASE_URI'] = TEST_DATABASE_URI
    db = SQLAlchemy(app)
    return db

Unfortunately this is not working since the defined models inherit from db.Model which is not defined obviously when the classes are evaluated. Is there any way how I can make the classes/models to inherit from the db.Model class which is only accessible through the db object when one of the methods above is called?

4
  • Correct me if I got this wrong: You have an app running in production, and in certain times you'd like to access to production DB, and some times to test DB, right? Commented Jun 8, 2014 at 21:50
  • I'm not familiar with SQLAlchemy, but perhaps you can inherit from SQLAlchemy.Model instead? Commented Jun 8, 2014 at 21:55
  • @cemkyg Sort of: I have some unit tests which should access the test database while the production code should access the production database. I could solve this problem by creating two modules one for production and one for tests within which I create a db object on initialization before all model definitions - but then I would have to define all models twice which is undesirable for me. Commented Jun 8, 2014 at 21:55
  • It seems as if there is no SQLAlchemy.Model - at least in the flask wrapped version I use. Commented Jun 8, 2014 at 22:01

1 Answer 1

2

I solved it now via:

db = SQLAlchemy()

#models here

def create_app():
    app = Flask(__name__)
    #db configuration
    db.init_app(app)
    return db

as shown here http://pythonhosted.org/Flask-SQLAlchemy/api.html#flask.ext.sqlalchemy.SQLAlchemy

Sign up to request clarification or add additional context in comments.

2 Comments

That's correct. Can you accept the answer so this won't pop up in unanswered questions?
Thank you for the hint - accepting my own answer is still blocked for some hours.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.