pyeve / eve-sqlalchemy

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

Using own Flask-SQLAlchemy object does not work as described #85

Closed fubu closed 6 years ago

fubu commented 8 years ago

Section "Using Flask-SQLAlchemy" of the documentation states that the way to re-use my existing Flask-SQLAlchemy object is to subclass the SQL data layer object and provide it to Eve. This does not work as described; instead, your own Flask-SQLAlchemy object is used when following the docs.

models.py:

from eve_sqlalchemy import SQL as _SQL
from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

class SQL(_SQL):
    driver = db

app.py:

from eve import Eve
from . import models

app = Eve(settings={'DOMAIN': {}}, data=models.SQL)

testing:

>>> import models, app
>>> app.data.driver is models.db
False
>>> app.data.driver is models._SQL.db
True

As far as I can see SQL.init_app is responsible for that. Eve itself initialises the data layer by first setting the instance-level driver to None (as the comment in your source already acknowledges), then calling init_app on the data layer, which reverts SQL.driver to the module-level SQL.db. My own driver set on the class-level as proposed by the docs is never ever used.

As for a solution, I think it's desireable to be able to provide your own Flask-SQLAlchemy driver to eve-sqlalchemy. To solve the issue I replaced self.driver = db on line 45 with self.driver = self.__class__.driver (pull request incoming), which does the same thing when using the default data layer, but allowing to provide a custom Flask-SQLAlchemy driver.