Database migrations
-
Modify
model.py. -
Generate the migration:
(venv) $ flask db migrate -m "migration-name" -
Apply it:
(venv) $ flask db upgrade
More: The Flask Mega-Tutorial, Part IV: Database
Unit tests
A base test case that creates the application with a test configuration, pushes the application context and recreates the database for every test:
import unittest
from app import create_app, db
from config_tests import Config
class MmTestCase(unittest.TestCase):
def setUp(self):
self.app = create_app(Config)
self.appctx = self.app.app_context()
self.appctx.push()
db.create_all()
self.client = self.app.test_client()
def tearDown(self):
db.drop_all()
self.appctx.pop()
self.app = None
self.appctx = None
self.client = None
More: How to Write Unit Tests in Python, Part 3: Web Applications
Choices for a select field from an Enum
from enum import Enum
class ResourceType(Enum):
HTML = 0
VIDEO = 1
AUDIO = 2
IMAGE = 3
PDF = 4
HTTP = 5
EPUB = 6
def get_choices():
return [(r.value, r.name) for r in ResourceType]
Error pages without an error loop
Rendering error pages from a blueprint can cause an avalanche of errors when the error handler itself fails. Discussion and solution: How to render error pages in Flask not causing errors loop
