tedivm · GitHub

Expected Behavior

The following code should create a new URL converter that converts a specific field to a model (or None).

class ModelConverter(BaseConverter):
    def to_python(self, value):
        return models.Example.query.filter(models.Example.name == value).first()
    def to_url(self, value):
        if isinstance(value, str):
            return value
        return value.name

Actual Behavior

The converters don't have access to the app context so an error is thrown.

Bad Solution

class OrganizationConverter(BaseConverter):
    app = None
    def to_python(self, value):
        with self.app.app_context():
            return repositories.Organization.query.filter(repositories.Organization.name == value).first()
    def to_url(self, value):
        if isinstance(value, str):
            return value
        return value.name

This solution tries to get around it by creating a new app context. The problem is that the context disappears, killing the database session at the same time. This prevents SQLAlchemy features (such as lazy loading).

Environment

  • Python version: 3.6 and 3.7
  • Flask version: 1.0.2
  • SQLAlchemy version: 1.2.17
  • Flask-SQLAlchemy version: 2.3.2
  • Werkzeug version: 0.14.1

Additional Resources

This issue has also come up on stack overflow

Read the original on github.com ↗