3

目标是编写一个简单的Flask 扩展。我使用Flask Extension Development 参考作为指南。我还研究了flask -sqlalchemy和flask-mongoengine源代码以获取线索。

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

使用工厂方法的超级简单的 Flask 应用程序。

# 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

遵循 Flask 参考作为指南的示例扩展。在上下文中返回 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()

我开始有问题的地方。我收到RuntimeError: Working outside of application context错误。

# 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

我不能with app.app_context:在我的GraphMixin课堂上使用,因为我没有构建它就无法访问app(我应该在app每次访问user模型时创建一个实例)。

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

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

4

0 回答 0