[python] Create database with flask-sqlalchemy

On previous post I have used a pure SQLAlchemy module to just create the database, this time I am using Flask_SQLAlchemy to do it, which makes the creation simpler.

I will need to put in two configuration parameters:

  • SQLALCHEMY_DATABASE_URI
  • SQLALCHEMY_TRACK_MODIFICATIONS

For the configuration I have put them in a config.py file.

SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://username:password@192.168.1.220/datalab'
SQLALCHEMY_TRACK_MODIFICATIONS = False

As usual you need to create the database first before connecting from SQLAlchemy.

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)

# The same can be done this way:
# app.config['SQLALCHEMY_DATABASE_URI'] = your DB connection string
# app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config.from_pyfile('config.py')

# pass in the app into SQLAlchemy to create a db session.
db = SQLAlchemy(app)

# declare the class for the model. 
class Test(db.Model):
    id = db.Column(db.Integer, primary_key=True)

if __name__ == '__main__':
    # The creation starts here.
    db.create_all()
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s