SQLAlchemy / Flask / PostgreSQL pool connection

不羁的心 提交于 2019-12-10 01:26:57

问题


After having played for a long time with Django, I'm trying a bit of Flask with SQLAlchemy, and I must say I quite like it. However there is something that I don't get: I have a small Flask / SQLAlchemy app that uses PostgreSQL. In my __init__.py file I have:

from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config.from_object('settings')
db = SQLAlchemy(app)

I wanted to know:

  1. Is there automatic connection pooling ? Or does every call to Model.query... create a new connection to the database?
  2. If not, how can I configure it?
  3. If yes, what are the defaults, how can I modify the values?

Thank you very much for you help !


回答1:


Flask-SQLAlchemy creates a SQLAlchemy engine using the create_engine method in SQLAlchemy, which you can read about some of the options and defaults in the documentation for the create_engine function. According to the Flask-SQLAlchemy documentation, you can specify some of the configuration options specific to pooling. You can set those values in various ways, which you can read about in the Flask configuration. You already have a settings configuration module, so you can add to your config file something like...

SQLALCHEMY_POOL_SIZE=10

So, yes, there is automatic connection pooling. This is provided by SQLAlchemy by default. As of the posting of this answer, Flask-SQLAlchemy allows you to modify some of these options using the configuration file (although it appears there is an old pull request to allow you to specify ANY create_engine parameter).

If you need more support for configuring the SQLAlchemy engine than Flask-SQLAlchemy provides, you can either use SQLAlchemy without the Flask-SQLAlchemy wrapper, or modify Flask-SQLAlchemy (perhaps merging the pull request) to allow this.




回答2:


NullPool can be set on the create_engine method

` from sqlalchemy.pool import NullPool
  engine = create_engine('db connection url',poolclass=NullPool)`


来源:https://stackoverflow.com/questions/15939104/sqlalchemy-flask-postgresql-pool-connection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!