Guest User

Untitled

a guest
Dec 3rd, 2019
82
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import mysql.connector
  2. from flask import g
  3.  
  4. class MySQL:
  5. def __init__(self, app):
  6. self.app=app
  7. self.app.teardown_appcontext(self.close_db)
  8.  
  9. def connection(self):
  10. if 'db' not in g:
  11. g.db = self.connect()
  12. return g.db
  13.  
  14. def connect(self):
  15. return mysql.connector.connect(**self.config())
  16.  
  17. def config(self):
  18. return {
  19. 'user': self.app.config['MYSQL_USER'],
  20. 'password': self.app.config['MYSQL_PASSWORD'],
  21. 'host': self.app.config['MYSQL_HOST'],
  22. 'database': self.app.config['MYSQL_DATABASE'],
  23. }
  24.  
  25. def close_db(self, e=None):
  26. db = g.pop('db', None)
  27. if db is not None:
  28. db.close()
RAW Paste Data