Get It Done! Part 2: Database Configuration

Notes

Begin by starting MAMP, starting the servers, and going to phpMyAdmin.

Now we'll create a new user and database for our Get It Done! application. A good design principle is that for each application you have one database, for each database, one user. This keeps privileges and permissions separated across applications. You can review the basic steps in written form here.

If you don't already have flask-env activated, activate it now. Then run:

conda install -c conda-forge flask-sqlalchemy

After this installation completes, run the following:

conda install pymysql

Now, amend your main.py by adding the following four lines:

from flask_sqlalchemy import SQLAlchemy 
# Note: the connection string after :// contains the following info:
# user:[email protected]:portNumber/databaseName

app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://get-it-done:[email protected]:8889/get-it-done'
app.config['SQLALCHEMY_ECHO'] = True
db = SQLAlchemy(app)

Next we'll continue modifying main.py and create a persistent class for database data:

class Task(db.Model):

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(120))

    def __init__(self, name):
        self.name = name

Be sure to shield app.run by enclosing it in an if condition:

if __name__ == '__main__':
    app.run()

Back in the terminal, start a python shell by running the command python. Then import db and create the tables:

> from main import db,Task
> db.create_all()

Now run the following commands one at a time to add data to the database:

>>> new_task = Task('finish ORM lesson 2')
>>> db.session.add(new_task)
>>> another_task = Task('post lesson video')
>>> db.session.add(another_task)
>>> db.session.commit()

To get data from the database, run the following:

>>> tasks = Task.query.all()
>>> tasks[0].name

Code

View the final code for this lesson.

References