Skip to content

Instantly share code, notes, and snippets.

@IvanBayan
Forked from macloo/local_db_test.py
Created January 14, 2022 09:07
Show Gist options
  • Save IvanBayan/08ef3538c7bf40ece67563c9f72f91bb to your computer and use it in GitHub Desktop.
Save IvanBayan/08ef3538c7bf40ece67563c9f72f91bb to your computer and use it in GitHub Desktop.
Test your MySQL database connection for Flask-SQLAlchemy
#!/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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment