Get It Done! Part 2: Database Configuration
Important Note:
This series of videos uses MAMP, PHPMyAdmin, and MySQL. WE ARE NOT USING THESE TOOLS. Instead we are using TablePlus and Sqlite3.
The code examples below ARE slightly different from the code in the video
Each difference is marked with a DIFFERENT CODE ALERT marker
Notes
If you don't already have flask-env activated, activate it now. Then run:
conda install -c conda-forge flask-sqlalchemy
If instead you are using pipenv you may run:
pipenv install flask-sqlalchemy
Or if you prefer installing the dependency globally:
pip install flask-sqlalchemy
After this installation completes, amend your main.py by adding the following six lines:
DIFFERENT CODE ALERT
import os
from flask_sqlalchemy import SQLAlchemy
DIFFERENT CODE ALERT
project_dir = os.path.dirname(os.path.abspath(__file__))
app.config['SQLALCHEMY_DATABASE_URI'] = "sqlite:///{}".format(os.path.join(project_dir, "get-it-done.db"))
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 (or python3 depending on your installation). 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.