[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:


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

SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://username:password@'

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

# 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.

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 )

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