在Flask的应用程序上下文中保持py2neo连接

时间:2017-05-27 22:46:04

标签: python flask neo4j py2neo werkzeug

我在我的烧瓶项目中使用了没有flask extension的py2neo(因为它表现得非常strangely)。
我试图做的是在应用程序上下文中保留我的数据库连接(因为它在整个请求处理期间保留,对吧?)。

根据flask的文档,我有以下代码:

def get_neo4j():
    with app.app_context():
        neo4j = getattr(g, '_neo4j', None)
        if neo4j is None:
            connection_string = http blah blah blah
            neo4j = g._neo4j = Graph(connection_string)
        return neo4j  

这是对的吗?如何编辑上述代码以受益于werkzeug的本地代理?

1 个答案:

答案 0 :(得分:1)

确定, 在阅读了extensions上的Flask的文档之后,开发我自己的类来保持连接活着很简单:

from py2neo import Graph
from flask import current_app

try:
    from flask import _app_ctx_stack as stack
except ImportError:
    from flask import _request_ctx_stack as stack


class Neo4jConnection(object):

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

    def init_app(self, app):
        if hasattr(app, 'teardown_appcontext'):
            app.teardown_appcontext(self.teardown)
        else:
            app.teardown_request(self.teardown)

    def connect(self):
        # Read configuations from app config
        return Graph(bolt=True,
                     host=current_app.config['NEO4J_SERVER_ADDRESS'],
                     bolt_port=current_app.config['NEO4J_PORT'],
                     user=current_app.config['NEO4J_USER'],
                     password=current_app.config['NEO4J_PASSWORD'],)

    def teardown(self, exception):
        ctx = stack.top
        if hasattr(ctx, 'neo4j_db'):
            ctx.neo4j_db = None

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

现在使用工厂模式使其正常工作:

初始化:

neo4j = Neo4jConnection()
neo4j.init_app(app)

用法:

myneo = Neo4jConnection().connection
myneo.push(.....)

我测试了它。希望它是正确的。