I have a Python web server configured using Flask and a database using 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". Or a better way of doing this?
Apologies if it is too basic, I am relatively new using Python and 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.