Articles

Flask: migrations, unit tests, select choices and error pages

· 1 min readflaskpythonsoftdevel

Database migrations

  1. Modify model.py.

  2. Generate the migration:

    (venv) $ flask db migrate -m "migration-name"
  3. 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

Learning resources

All articles

See also

pythonqtsoftdevel

Python and PySide2: small recipes

Testing console input and output, upgrading all pip packages, generating CLIs, dialogs and resources in PySide2, and a dark theme for Jupyter Notebook.

softdevelPL

Notuj swobodnie, niech AI zadba o resztę

Od zawsze, im więcej notowałem, tym mniej użyteczny stawał się mój notes, czy to papierowy, czy elektroniczny.

linuxsoftdevel

Linux server administration: a practical cheatsheet

Security checks, certificates, scheduled jobs, disks and backups, network diagnostics and basic system configuration — commands I use on Linux servers.