我正在创建一个REST API。我正在使用Python,Flask和MySQL从数据库中获取数据并以JSON格式呈现它们。但我有一个问题。
REST API与NGINX和uWSGI一起提供,一切运行良好。索引页面保持可用,并且不会超时但是与数据库建立连接的页面会起作用。页面大约需要15分钟才能无响应。在phpmyadmin或navicat等RDBMS中不会发生此问题。
它可能是什么,我该如何解决?下面的REST API代码。
# using python version 2.7.10
from flask import Flask, jsonify, request, session
import mysql.connector.pooling
#Make a connection with the DB
dbconfig = {
"host" : "12.34.5.78",
"database": "db",
"user": "user",
"password": "pass"
}
conn = mysql.connector.connect(pool_name = "mypool",
pool_size = 6,
**dbconfig)
#Define the root
app = Flask(__name__)
#Landings page
@app.route('/')
def index():
return "Hello World."
# return all resources by name
@app.route('/resources', methods=['GET'])
def allResourceNames():
conn1 = mysql.connector.connect(pool_name="mypool")
reader = conn1.cursor()
query = ("SELECT name FROM resources")
reader.execute(query)
resources = []
for name in reader:
resources.append({'name' : name[0]})
reader.close()
conn1.close()
return jsonify({"resources" : resources})
if __name__ == "__main__":
app.run(debug=True)
答案 0 :(得分:0)
以上所有评论都是正确的。以下是在每次请求后修改代码以关闭数据库连接的方法。每次调用get_db
并在每次请求后关闭它都会创建一个新的数据库连接。
# using python version 2.7.10
import mysql
from flask import Flask, jsonify, request, session, g
def connect_db():
conn = mysql.connector.connect(user='user', password='pass',
host='12.34.5.67', database='db')
return conn
def get_db():
if not hasattr(g, 'db'):
g.db = connect_db()
return g.db
#Define the root
app = Flask(__name__)
# close db at end of each request
@app.teardown_appcontext
def close_db(_):
if hasattr(g, 'db'):
g.db.close()
#Landings page
@app.route('/')
def index():
return "Hello World."
# return all resources by name
@app.route('/resources', methods=['GET'])
def allResourceNames():
reader = get_db()
query = ("SELECT name FROM resources")
reader.execute(query)
resources = []
for name in reader:
resources.append({'name' : name[0]})
return jsonify({"resources" : resources})
if __name__ == "__main__":
app.run(debug=True)