Skip to content

Commit

Permalink
Fix binding of db.session to ModelSchema classes
Browse files Browse the repository at this point in the history
  • Loading branch information
sloria committed May 1, 2015
1 parent dc8457b commit e33d821
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 5 deletions.
4 changes: 3 additions & 1 deletion flask_marshmallow/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,8 @@ class Marshmallow(object):
To use it, instantiate with an application::
from flask import Flask
app = Flask(__name__)
ma = Marshmallow(app)
Expand Down Expand Up @@ -112,5 +114,5 @@ def init_app(self, app):
# If using Flask-SQLAlchemy, attach db.session to ModelSchema
if has_sqla and 'sqlalchemy' in app.extensions:
db = app.extensions['sqlalchemy'].db
self.ModelSchema.Meta.sqla_session = db.session
self.ModelSchema.OPTIONS_CLASS.session = db.session
app.extensions[EXTENSION_NAME] = self
7 changes: 4 additions & 3 deletions flask_marshmallow/sqla.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,19 +15,20 @@ class SchemaOpts(msqla.SchemaOpts):
class Meta. The actual session from `flask_sqlalchemy` gets bound
in `init_app`.
"""
session = DummySession()

def __init__(self, meta):
if not hasattr(meta, 'sqla_session'):
meta.sqla_session = DummySession()
meta.sqla_session = self.session
super(SchemaOpts, self).__init__(meta)

class ModelSchema(msqla.ModelSchema, Schema):
"""ModelSchema that generates fields based on the
`model` class Meta option, which should be a
``db.Model`` class from `flask_sqlalchemy`. Uses the
scoped session from `flask_sqlalchemy` by default.
scoped session from Flask-SQLAlchemy by default.
See `<marshmallow_sqlalchemy.ModelSchema>` for more details
See `marshmallow_sqlalchemy.ModelSchema` for more details
on the `ModelSchema` API.
"""
OPTIONS_CLASS = SchemaOpts
10 changes: 9 additions & 1 deletion test_flask_marshmallow.py
Original file line number Diff line number Diff line change
Expand Up @@ -246,15 +246,23 @@ def extma(self, extapp):
@pytest.yield_fixture()
def models(self, db):
class AuthorModel(db.Model):
__tablename__ = 'author'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(255))

class BookModel(db.Model):
__tablename__ = 'book'
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(255))
author_id = db.Column(db.Integer, db.ForeignKey('author.id'))
author = db.relationship('AuthorModel', backref='books')

db.create_all()

class _models:
def __init__(self):
self.Author = AuthorModel

self.Book = BookModel
yield _models()
db.drop_all()

Expand Down

0 comments on commit e33d821

Please sign in to comment.