Can someone share example codes in Flask on how to access a MySQL DB? There have been documents showing how to connect to sqlite but not on MySQL.
Thank you very muc
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://username:password@server/db'
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True)
email = db.Column(db.String(120), unique=True)
def __init__(self, username, email):
self.username = username
self.email = email
def __repr__(self):
return '<User %r>' % self.username
help link
we can use mysql using app.config to set the configurations. in future you should not use only development environment, you will need to automatically set the env while in production env.
we should always go for oops concept
firstly we should make a file where it will check and set mysql config for production/development env and set the values to app.config.
# config.py you can put this file anywhere in the project
class Config(object):
DEBUG = False
TESTING = False
class DevelopmentConfig(Config):
"""
Development configurations
"""
MYSQL_DATABASE_USER = 'root'
MYSQL_DATABASE_PASSWORD = ''
MYSQL_DATABASE_HOST = '127.0.0.1'
MYSQL_DATABASE_DB = 'FlaskProject' # can be any
DEBUG = True
class ProductionConfig(Config):
"""
Production configurations
"""
MYSQL_DATABASE_USER = 'yourusername'
MYSQL_DATABASE_PASSWORD = 'yourpassword'
MYSQL_DATABASE_HOST = 'linktoyourdb' # eg to amazone db :- yourdbname.xxxxxxxxxx.us-east-2.rds.amazonaws.com
MYSQL_DATABASE_DB = 'yourdbname'
DEBUG = False
after that use pip3 install flask-mysql
# app.py
from flask import Flask,
from flaskext.mysql import MySQL
app = Flask(__name__)
mysql = MySQL()
if app.config['ENV'] == 'production':
app.config.from_object('config.ProductionConfig')
else:
app.config.from_object('config.DevelopmentConfig')
mysql.init_app(app)
@app.route('/')
def yrfunname():
try:
conn = mysql.connect()
cursor = conn.cursor()
cursor.execute("SELECT * from yrtablename")
data = cursor.fetchone()
conn.commit()
cursor.close()
return 'success', 200
except Exception as fail:
print("Something is wrong with your database user name or password {}".format(fail))
Now flask will auto handle the env. you only need to push yr code to production. As your project become bigger you dont have to make db conn again and again. You can use another py file for db connection and use that db connection anywhere in the project.
I am also new to this but i have done lot of research then got this.