<style>
.present {
text-align: left;
}
</style>
# Migrations with Flask
## Week 18 Day 4
---
## Lecture Videos 1 (23 min)
Watch:
- Flask-Migrate Demo (19:16)
---
### Setting Up Flask-Migrate
1. Install packages (`alembic` and `flask-migrate`).
```bash
pipenv install alembic flask-migrate
```
2. Import `Migrate` from `flask_migrate` and use it to configure your migrations (in the file where you are defining your Flask application).
```python=
# add this to the top of the file with the imports
from flask_migrate import Migrate
# this goes after your app is instantiated
Migrate(app, db)
```
---
### Setting Up Flask-Migrate
3. Initialize your migrations repo.
```bash
flask db init
```
4. Create a migration file.
```bash
flask db migrate
```
5. Apply your migrations to your database.
```bash
flask db upgrade
```
---
### Workflow
When you make changes to your models:
6. Run migrate to get a new migration script.
```bash
flask db migrate
```
7. Run upgrade to apply the changes.
```bash
flask db upgrade
```
---
### Downgrading
Downgrading shouldn't be a very common part of your workflow. If you want to downgrade a migration, you can use the `downgrade` command.
To undo a single migration:
```bash
flask db downgrade
```
---
## Lecture Videos 2 (15 min)
Watch:
- JSON With Flask (12:00)
---
### Model Instances vs. Dictionaries
Recall that, in JavaScript, we typically use objects for two purposes: as a collection of key/value pairs, and also as a collection of methods and properties.
In Python, key/value pairs in dictionaries are not the same as attributes on objects.
```python=
widget = Widget.query.get(1)
print(widget) # <Widget 1>
```
If you try to send a model instance object from your server, that won't work. However, if you have a dictionary, that will be automatically converted to JSON.
---
### Returning JSON from Python
We need to convert our database objects into dictionaries so that we can use our Flask back-end as an API.
```python=
widget = Widget.query.get(1)
widget_dict = {
"id": widget.id,
"color": widget.color,
}
print(widget_dict) # Flask can automatically convert this to JSON
```
---
### Writing a `to_dict()` method
We can make our code `DRY`er by adding a method to our model classes to convert model instances to dictionaries.
That way we don't have to rewrite the same code on different routes when we send data to our front-end.
```python=
class Widget(db.Model):
__tablename__ = "widgets"
id = db.Column(db.Integer, primary_key=True)
color = db.Column(db.String(50), nullable=False)
# some lines skipped
def to_dict(self):
return {
"id": self.id,
"color": self.color,
}
```