Created
May 5, 2020 18:44
-
-
Save rueian/83d316a3333af35be1af7a4d4c7262a2 to your computer and use it in GitHub Desktop.
flask with mysql connection pool
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from flask import Flask, g | |
| import os | |
| import mysql.connector.pooling | |
| app = Flask(__name__) | |
| cnxpool = mysql.connector.pooling.MySQLConnectionPool( | |
| host=os.getenv('MYSQL_HOST', '127.0.0.1'), | |
| user=os.getenv('MYSQL_USER', 'flasklab'), | |
| password=os.getenv('MYSQL_DATABASE', 'flasklab'), | |
| database=os.getenv('MYSQL_PASSWORD', 'flasklab'), | |
| pool_name="flasklab", | |
| pool_size=10) | |
| @app.before_request | |
| def acquire_conn(): | |
| if 'cxn' not in g: | |
| print('getting connection...') | |
| g.cxn = cnxpool.get_connection() | |
| @app.teardown_request | |
| def release_conn(exception): | |
| if 'cxn' in g: | |
| print('releasing connection...') | |
| g.cxn.close() | |
| @app.route('/') | |
| def index(): | |
| print('start transaction to insert user...') | |
| g.cxn.start_transaction() | |
| cursor = g.cxn.cursor(prepared=True) | |
| cursor.execute('insert into user_info (name) values (%s)', ('my_name',)) | |
| cursor.execute('insert into users (info_id) values (LAST_INSERT_ID())') | |
| g.cxn.commit() | |
| cursor.close() | |
| print('new cursor to query data...') | |
| cursor = g.cxn.cursor(prepared=True) | |
| cursor.execute('select id, info_id from users order by id desc limit %s', (1,)) | |
| for (user_id, info_id) in cursor: | |
| print('user inserted: user_id={} info_id={}'.format(user_id, info_id)) | |
| cursor.close() | |
| return 'Hello World!' | |
| if __name__ == '__main__': | |
| app.run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment