Last active
March 12, 2024 18:00
-
-
Save macloo/35bdd1648cadf1ca6e910d5fbf8fa754 to your computer and use it in GitHub Desktop.
Test your MySQL database connection for Flask-SQLAlchemy
This file contains 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
#!/Users/username/Documents/python/projectname/env/bin/python | |
# change username and projectname above to match yours - the path must match the path in YOUR virtualenv | |
""" | |
edit line 1 to match what YOU get when you are in YOUR virtualenv and type: | |
which python | |
# NO SPACES in first 3 chars in line 1: #!/ | |
# make sure env is activated! | |
# make sure you have "started all" in XAMPP! | |
# code below works for a MySQL database in XAMPP on Mac OS | |
# pymysql can be installed with pip: pip install pymysql | |
""" | |
import pymysql | |
from flask import Flask | |
from flask_sqlalchemy import SQLAlchemy | |
app = Flask(__name__) | |
# this userpass assumes you did not create a password for your database | |
# and the database username is the default, 'root' | |
userpass = 'mysql+pymysql://root:@' | |
basedir = '127.0.0.1' | |
# change to YOUR database name, with a slash added as shown | |
dbname = '/sockmarket' | |
# this socket is going to be very different on a Windows computer | |
socket = '?unix_socket=/Applications/XAMPP/xamppfiles/var/mysql/mysql.sock' | |
dbname = dbname + socket | |
# put them all together as a string that shows SQLAlchemy where the database is | |
app.config['SQLALCHEMY_DATABASE_URI'] = userpass + basedir + dbname | |
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True | |
# this variable, db, will be used for all SQLAlchemy commands | |
db = SQLAlchemy(app) | |
# this route will test the database connection and nothing more | |
@app.route('/') | |
def testdb(): | |
try: | |
db.session.query("1").from_statement("SELECT 1").all() | |
return '<h1>It works.</h1>' | |
except: | |
return '<h1>Something is broken.</h1>' | |
if __name__ == '__main__': | |
app.run(debug=True) |
This will work in 2024 db.session.execute(text('SELECT 1'))
Thank you!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This will work in 2024
db.session.execute(text('SELECT 1'))