[英]Flask-mysqldb database cursor
I have a Python web server configured using Flask and a database using flask-mysqldb. 我有使用Flask配置的Python Web服务器和使用flask-mysqldb的数据库。 Currently, I have the database connection at the start of the application, something like this:
当前,我在应用程序的开始处具有数据库连接,如下所示:
from flask_mysqldb import MySQL
app = Flask(__name__)
mysql = MySQL(app)
And each route has its own cursor in this way: 每个路线都以这种方式拥有自己的游标:
@app.route('/action')
def execute_action():
cursor = mysql.connection.cursor()
# processing
cursor.connection.close()
@app.route('/load')
def load_data():
cursor = mysql.connection.cursor()
# processing
cursor.connection.close()
However, now I need to access that same database connection from within other classes and functions, but passing the connection as a parameter is not an option. 但是,现在我需要从其他类和函数中访问相同的数据库连接,但是不能将连接作为参数传递。 Is there anyway I can declare that global and access it from other classes?
无论如何,我可以声明该全局变量并从其他类访问它吗? either "app" or "mysql".
“ app”或“ mysql”。 Or a better way of doing this?
还是更好的方法呢?
Apologies if it is too basic, I am relatively new using Python and Flask 抱歉,如果太基础了,我是使用Python和Flask的新手
The connection already is global. 该连接已经是全局的。 Accessing
mysql.connection
within the same request will yield the same connection , no matter where you access it from. 在相同的请求中访问
mysql.connection
都会产生相同的连接 ,无论您从何处访问它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.