我已经创建了一个以mysql为后端的烧瓶应用程序。要启动DB连接,我使用了以下内容:
@app.before_request
def db_connect():
try:
g.db = MySQLdb.connect(host="localhost", user="root", passwd="", db="ddb",cursorclass=MySQLdb.cursors.DictCursor,autocommit=True)
except Exception as e:
print(e)
@app.teardown_request
def db_disconnect(exception=None):
try:
if g.db is not None:
g.db.close()
except Exception as e:
print(e)将其加载到init_py中。但是我检查了这个mysql打开和关闭多少次,它的命运。因为连接是打开和关闭的,即使css/js文件请求调用。我在所有函数中调用g.db。怎样才能避免这种情况?
发布于 2018-10-15 15:12:13
问得好。基本上,您提供的代码在每个请求之前启动一个db连接。每个访问的url都是一个请求--包括检索到的图像或样式表-,所以这很常见。
怎么办?
flask + WSGI,并将这个小脚本添加到WSGIDaemonProcess行的WSGIDaemonProcess文件中。
别名“/静态/”"/home/user/webapps/flask_app/flask_app/static/“<目录"/home/user/webapps/flask_app/flask_app/static/">需要所有授予class / API,并缓存最常见的请求。当然,只适用于select。看这个漂亮工程。
类数据库():@threaded_cached_property_with_ttl(ttl=60*60) #,按秒计算,def some_popular_query():connection = MySQLdb.connect(host="localhost",user=“,passwd=”,db=“))返回connection.get_query()Illustration
举个例子,假设我们有一个简单的template/main.html网站。
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"</script>
<script src="static/style/test.css"></script>
</head>
<body>
{{message}}
<img src="static/img/test.png' />
</body>和index.py
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return render_template('index.html', message='Hello world')使用您描述的烧瓶站点,您将有一个页面和模板请求、另一个样式表请求和另一个图像请求。这是对你的数据库的三个调用!
https://stackoverflow.com/questions/52818695
复制相似问题