Python 烧瓶扩展、上下文和Neo4j

Python 烧瓶扩展、上下文和Neo4j,python,flask,neo4j,py2neo,flask-extensions,Python,Flask,Neo4j,Py2neo,Flask Extensions,目标是编写一个简单的Flask扩展。我用这本书作为指南。我还研究了代码和源代码以寻找线索 我的问题是在视图之外使用Neo4j连接。我遇到了应用程序上下文问题,似乎陷入了一个循环 使用工厂方法的超级简单烧瓶应用程序 # project.app from flask import Flask, register_blueprint from project.extensions import graph from project.blueprints.user import user_bluepr

目标是编写一个简单的Flask扩展。我用这本书作为指南。我还研究了代码和源代码以寻找线索

我的问题是在视图之外使用Neo4j连接。我遇到了应用程序上下文问题,似乎陷入了一个循环

使用工厂方法的超级简单烧瓶应用程序

# 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
以烧瓶参考后的样品延伸为指南。在上下文中返回Neo4j连接

# 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()
我开始有问题了。我收到
运行时错误:在应用程序上下文之外工作
错误

# 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)
简单的用户模型,继承了
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
在我的
GraphMixin
类中,我不能将
与app.app\u context:
一起使用,因为如果不构建
应用程序,我就无法访问它(每次访问
用户
模型时,我都应该创建一个
应用程序
实例)

如何将扩展嵌入到应用程序上下文中,以便在视图内部和外部使用

Python==3.6

Flask==0.12

Py2neo==3.1.2