如何解决flask sqlalchemy连接超时错误(队列池溢出限制)



我制作了一个名为"/get_report"它接受用户的一些输入,并通过对数据库进行一些搜索查询来根据输入返回数据。如果我多次点击同一个API,比如7-8次,在第9次点击时抛出错误";sqlalchemy.exc.TimeoutError:达到大小为5的队列池限制溢出10,连接超时,超时30.00(此错误的背景信息:https://sqlalche.me/e/14/3o7r)&";。

这是我的主要.py:

from flask_sqlalchemy import SQLAlchemy
from flask import Flask, jsonify, request
from helper import * 
from models.tx import *

app = Flask(__name__)
db = SQLAlchemy()
DB_URL = 'postgresql://postgres:postgres@localhost/test_db'
engine = create_engine(DB_URL)
Session = sessionmaker(engine)
app.config['SQLALCHEMY_DATABASE_URI'] = DB_URL
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db.init_app(app)
@contextmanager
def session_manager():
s = Session()
try:
yield s
except:
s.rollback()
raise
finally:
s.close()
@app.route('/get_report', methods=['POST'])
def get_report():
try:
vendor = request.form['vendor']
circle = request.form['circle']
c_name = request.form['c_name']
c_port = request.form['c_port']
all_ssr = request.form['all_ssr']
data_list = []
table_name = get_table_by_vendor(vendor, circle)
if table_name != None:
with session_manager() as s:
if all_ssr == 'SSR':
result = s.query(table_name).distinct(table_name.label, table_name.c_node, 
table_name.c_port, table_name.z_port, table_name.z_node) 
.filter(and_((or_( and_(table_name.c_node == c_name, table_name.c_port == c_port), 
and_(table_name.z_node == c_name, table_name.z_port == c_port ))), 
(table_name.__table__.c[field_name].like('SSR%')))).all()  
elif all_ssr == 'ALL':
# Get all the records 
result = s.query(table_name).distinct(table_name.label, table_name.c_node, 
table_name.c_port, table_name.z_port, table_name.z_node) 
.filter(or_( and_(table_name.c_node ==c_name, table_name.c_port == c_port), 
and_(table_name.z_node == c_name, table_name.z_port == c_port ))).all()
else:
result = []   
# Preparing JSON data to send
for item in result:
port = c_port if c_port != '' else (item.c_port if item.c_node == c_name else item.z_port)
data_dict = {'user': item.user, 'port': item.port, 'rate':item.rate, 'down': item.down}
data_list.append(data_dict)
response = {"status": "Success", "message": "Successfully Fetched", "data": data_list}
return jsonify(response)

if __name__ == '__main__':
app.run(host='0.0.0.0', port = 5000,debug = True)

这是我的型号/tx.py:

class C_Segment(db.Model):
__tablename__ = 'c_segment'
id = db.Column(db.Integer, primary_key=True)
c_node = db.Column(db.String(350), nullable=False)
c_port = db.Column(db.String(200), nullable=False)
label = db.Column(db.String(350), nullable=False)
z_port = db.Column(db.String(200), nullable=False)
z_node = db.Column(db.String(200), nullable=False)
user = db.Column(db.String(200), nullable=False)
down = db.Column(db.String(200), nullable=False)
port = db.Column(db.String(200), nullable=False)
rate = db.Column(db.String(200), nullable=FaI
return '<id {}>'.format(self.id)

我在谷歌上搜索了很多,发现了很多相关的内容,但没有一个对我有效。我也尝试过增加池大小和溢出大小,但什么都没有发生。我不知道确切的问题在哪里。在过去的两天里,我一直被困在这个问题上,并浏览了许多堆栈溢出内容和flask sqlalchemy会话文档。

池中有一组连接,例如15(池中有5个,可能溢出时有10个(。如果请求处理时间长于连接签出超时(您将在可用连接上等待多长时间,默认为30秒(,则会出现此错误(所有15个连接都很忙,您的请求必须等待可用连接-并且只等待30秒,之后会出现错误(。你考虑过查询优化吗?你桌上有多少张唱片?请求持续多久?您可以使用配置您的SQL查询

EXPLAIN ANALYZE <query>

当然,您可以通过设置例如300秒(5分钟(来增加池超时:

app.config['SQLALCHEMY_POOL_TIMEOUT'] = 300

或者扩大游泳池的规模,但这并不能真正解决你的问题。请求中如此长的响应时间确实是糟糕的用户体验,并限制了客户端对应用程序的并发访问。因此,我建议您加快查询速度。

最新更新