Fix all flake8 warnings

This also fixes a bunch of missing imports in rare code paths.