3

The goal is to write a simple Flask extension. I'm using the Flask Extension Development reference as a guide. I've also studied the flask-sqlalchemy and flask-mongoengine source code for clues.

My problem is using the Neo4j connection outside of views. I'm bumping up against application context issues and I seem to be stuck in a circle.

Super simple Flask app using the factory method.

# project.app

from flask import Flask, register_blueprint
from project.extensions import graph
from project.blueprints.user import user_blueprint


def create_app():
    app = Flask(__name__)
    app.register_blueprint(user_blueprint)
    register_extensions(app)
    return app


def register_extensions(app):
    graph.init_app(app)
    return None

Sample extension following the Flask reference as a guide. Returns a Neo4j connection while in context.

# project.extensions

from flask import current_app, _app_ctx_stack
from py2neo import Graph

class Neo4j(object):
    def __init__(self, app=None):
        self.app = app
        if app is not None:
            self.init_app(app)

    def init_app(self, app):
        app.config.setdefault('NEO4J_URI', 'http://localhost:7474/db/data')
        app.teardown_appcontext(self.teardown)

    def connect(self):
        return Graph(current_app.config['NEO4J_URI'])

    def teardown(self, exception):
        ctx = _app_ctx_stack.top
        if hasattr(ctx, 'graph'):
            # py2neo doesn't support closing connections
            pass

    @property
    def connection(self):
        ctx = _app_ctx_stack.top
        if ctx is not None:
            if not hasattr(ctx, 'graph'):
                ctx.graph = self.connect()
            return ctx.graph

graph = Neo4j()

Where I start to have problems. I receive the RuntimeError: Working outside of application context error.

# project.utils.neo4j

from project.extensions import graph
from py2neo.ogm import GraphObject, Property


class GraphMixin(GraphObject):
    def add(self):
        # this works in sqlalchemy through "sessions"
        graph.connection.create(self)
        return self
    def delete(self):
        graph.connection.delete(self)

Simple user model which inherits the GraphMixin.

# project.blueprints.user.models

import uuid
from py2neo.ogm import Property
from project.utils.neo4j import GraphMixin


class User(GraphMixin):

    __primarykey__ = 'id'

    email = Property()
    password = Property()

    def __init__(self, email, password, **kwargs):
        self.id = str(uuid.uuid4().hex)
        self.email = email
        self.password = password  # yes this is encrypted in real life

    def get_id(self):
        return self.id

I cannot use with app.app_context: in my GraphMixin class because I don't have access to the app without building it (I should be creating an app instance each time I access the user model).

How can I embed the extension within the application context for use inside and outside of views?

Python==3.6
Flask==0.12
Py2neo==3.1.2

davidism
  • 121,510
  • 29
  • 395
  • 339
Jason Strimpel
  • 14,670
  • 21
  • 76
  • 106

0 Answers0