pyeve / eve-sqlalchemy

SQLAlchemy data layer for Eve-powered RESTful APIs
http://eve-sqlalchemy.readthedocs.io
Other
234 stars 70 forks source link

Internal SQLAlchemy object intialized without Flask app. #16

Closed edthedev closed 9 years ago

edthedev commented 9 years ago

Here's my very rough understanding of what may or may not be a problem - all learned while (not yet successfully) setting up an eve-sqlalchemy API.

Eve is an instance of a Flask app. Eve's constructor takes a parameter,

data = SQL

The SQL object constructs sets a default db, to a new instance of

flask_sqlalchemy.SQLAlchemy()

The constructor documentation for flask_sqlalchemy.SQLAlchemy has this to say about what should be built when:

From https://github.com/mitsuhiko/flask-sqlalchemy/blob/master/flask_sqlalchemy/__init__.py:

There are two usage modes which work very similarly. One is binding
the instance to a very specific Flask application::
    app = Flask(__name__)
    db = SQLAlchemy(app)
The second possibility is to create the object once and configure the
application later to support it::
    db = SQLAlchemy()
    def create_app():
    app = Flask(__name__)
    db.init_app(app)
    return app
The difference between the two is that in the first case methods like
:meth:`create_all` and :meth:`drop_all` will work all the time but in
the second case a :meth:`flask.Flask.app_context` has to exist.

So to get the best case instantiation of flask_sqlalchemy.SQLAlchemy, we need to be able to pass the Flask App object to it's constructor - in this case, the Eve subclass object, which has already instantiated the SQLAlchemy instance internally, without being able to do so.

I don't have a recommendation or solution here, just the suggestion that, to my admittedly very new to the situation analysis, this looks like it could be painful down the road.

I'm adding this here in the hopes that it will make an obvious improvement jump out to someone who better understands the overall architecture. :)

abkfenris commented 9 years ago

I can use an existingflask_sqlalchemy db by overriding the driver in SQL

from eve import Eve
from eve_sqlalchemy import SQL as _SQL
from eve_sqlalchemy import ValidatorSQL

# Really I have this somewhere else, and I'm just importing the db here
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy(app)

class SQL(_SQL):
  driver = db

def create_app():
  app = Eve(validator=ValidatorSQL, data=SQL)
  db.init_app(app)
  return app

Which I have working in proof_companion/app.py.

edthedev commented 9 years ago

Thanks @abkfenris. I might have stuck with eve-sqlalchemy if I had figured out how to do this, and been able to maintain my existing database declarations. My project uses flask-sqlalchemy and flask-restless now.

Maybe this example could get added to the eve-sqlalchemy examples, to assist future adopters?

abkfenris commented 9 years ago

I just added a section with #27

edthedev commented 9 years ago

Very cool. Thanks.