烧瓶的应用程序上下文和全局连接 [英] flask's application context and global connection

查看:73
本文介绍了烧瓶的应用程序上下文和全局连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建一个到数据库的连接池,该池可以被Flask中的请求重用.文档(0.11.x)建议使用应用程序上下文g来存储数据库连接.

I need to create a connection pool to database which can be reused by requests in Flask. The documentation(0.11.x) suggests to use g, the application context to store the database connections.

问题是在每个请求之前和之后都创建并销毁了应用程序上下文.因此,对创建的连接数没有限制,并且没有任何连接可以重用.我正在使用的代码是:

The issue is application context is created and destroyed before and after each request. Thus, there is no limit on the number of connection being created and no connection is getting reused. The code I am using is:

def get_some_connection():
    if not hasattr(g, 'some_connection'):
        logger.info('creating connection')
        g.some_connection = SomeConnection()
    return g.some_connection

并关闭连接

@app.teardown_appcontext
def destroy_some_connection(error):
    logger.info('destroying some connection')
    g.some_connection.close()

这是否是故意的,也就是说,flask每次都想创建一个新的连接,或者在我的代码中使用应用程序上下文存在一些问题.此外,如果有意解决此问题,可以使用全局连接.我知道,有些旧扩展将连接保留在app['extension']本身中.

Is this intentional, that is, flask want to create a fresh connection everytime, or there is some issue with the use of application context in my code. Also, if its intentional is there a workaround to have the connection global. I see, some of the old extensions keep the connection in app['extension'] itself.

推荐答案

否,您必须具有某种全局连接池. g使您可以在一个请求之间共享状态,因此可以在处理一个请求时在各种模板和函数之间共享状态,而不必传递该全局"状态,但这并不意味着可以代替模块全局变量(具有与模块相同的寿命.

No, you'll have to have some kind of global connection pool. g lets you share state across one request, so between various templates and functions called while handling one request, without having to pass that 'global' state around, but it is not meant to be a replacement for module-global variables (which have the same lifetime as the module).

您当然可以将数据库连接设置为g,以确保所有请求代码仅使用一个连接,但是您仍然可以从(模块)全局池中绘制连接.

You can certainly set the database connection onto g to ensure all of your request code uses just the one connection, but you are still free to draw the connection from a (module) global pool.

我建议您按每个线程创建连接 并将它们合并.您可以从头开始构建此对象(也许使用threading.local对象),也可以使用类似SQLAlchemy的项目,该项目随附 excellent 连接池实现.基本上,这就是 Flask-SQLAlchemy扩展的作用.

I recommend you create connections per thread and pool these. You can either build this from scratch (use a threading.local object perhaps), or you can use a project like SQLAlchemy which comes with excellent connection pool implementations. This is basically what the Flask-SQLAlchemy extension does.

这篇关于烧瓶的应用程序上下文和全局连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆