Python code clean-up (PEP-8 related and other)

- Add the UTF-8 marker to files without it.
- Fix some hanging indents.
- Change ''' into """ in docstrings.
- Enforce two blank line rule.
master
Patman64 10 years ago
parent 73480f4df4
commit 2a45b9f4ba
  1. 5
      {{cookiecutter.app_name}}/manage.py
  2. 3
      {{cookiecutter.app_name}}/tests/conftest.py
  3. 2
      {{cookiecutter.app_name}}/tests/factories.py
  4. 1
      {{cookiecutter.app_name}}/tests/test_config.py
  5. 1
      {{cookiecutter.app_name}}/tests/test_forms.py
  6. 1
      {{cookiecutter.app_name}}/tests/test_models.py
  7. 6
      {{cookiecutter.app_name}}/{{cookiecutter.app_name}}/app.py
  8. 2
      {{cookiecutter.app_name}}/{{cookiecutter.app_name}}/database.py
  9. 2
      {{cookiecutter.app_name}}/{{cookiecutter.app_name}}/public/__init__.py
  10. 2
      {{cookiecutter.app_name}}/{{cookiecutter.app_name}}/public/forms.py
  11. 6
      {{cookiecutter.app_name}}/{{cookiecutter.app_name}}/public/views.py
  12. 1
      {{cookiecutter.app_name}}/{{cookiecutter.app_name}}/settings.py
  13. 4
      {{cookiecutter.app_name}}/{{cookiecutter.app_name}}/user/__init__.py
  14. 2
      {{cookiecutter.app_name}}/{{cookiecutter.app_name}}/user/forms.py
  15. 1
      {{cookiecutter.app_name}}/{{cookiecutter.app_name}}/user/models.py
  16. 5
      {{cookiecutter.app_name}}/{{cookiecutter.app_name}}/utils.py

@ -1,8 +1,6 @@
#!/usr/bin/env python #!/usr/bin/env python
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import os import os
import sys
import subprocess
from flask_script import Manager, Shell, Server from flask_script import Manager, Shell, Server
from flask_migrate import MigrateCommand from flask_migrate import MigrateCommand
@ -21,12 +19,14 @@ TEST_PATH = os.path.join(HERE, 'tests')
manager = Manager(app) manager = Manager(app)
def _make_context(): def _make_context():
"""Return context dict for a shell session so you can access """Return context dict for a shell session so you can access
app, db, and the User model by default. app, db, and the User model by default.
""" """
return {'app': app, 'db': db, 'User': User} return {'app': app, 'db': db, 'User': User}
@manager.command @manager.command
def test(): def test():
"""Run the tests.""" """Run the tests."""
@ -34,6 +34,7 @@ def test():
exit_code = pytest.main([TEST_PATH, '--verbose']) exit_code = pytest.main([TEST_PATH, '--verbose'])
return exit_code return exit_code
manager.add_command('server', Server()) manager.add_command('server', Server())
manager.add_command('shell', Shell(make_context=_make_context)) manager.add_command('shell', Shell(make_context=_make_context))
manager.add_command('db', MigrateCommand) manager.add_command('db', MigrateCommand)

@ -11,6 +11,7 @@ from {{cookiecutter.app_name}}.database import db as _db
from .factories import UserFactory from .factories import UserFactory
@pytest.yield_fixture(scope='function') @pytest.yield_fixture(scope='function')
def app(): def app():
_app = create_app(TestConfig) _app = create_app(TestConfig)
@ -21,11 +22,13 @@ def app():
ctx.pop() ctx.pop()
@pytest.fixture(scope='session') @pytest.fixture(scope='session')
def testapp(app): def testapp(app):
"""A Webtest app.""" """A Webtest app."""
return TestApp(app) return TestApp(app)
@pytest.yield_fixture(scope='function') @pytest.yield_fixture(scope='function')
def db(app): def db(app):
_db.app = app _db.app = app

@ -5,6 +5,7 @@ from factory.alchemy import SQLAlchemyModelFactory
from {{cookiecutter.app_name}}.user.models import User from {{cookiecutter.app_name}}.user.models import User
from {{cookiecutter.app_name}}.database import db from {{cookiecutter.app_name}}.database import db
class BaseFactory(SQLAlchemyModelFactory): class BaseFactory(SQLAlchemyModelFactory):
class Meta: class Meta:
@ -20,4 +21,3 @@ class UserFactory(BaseFactory):
class Meta: class Meta:
model = User model = User

@ -2,6 +2,7 @@
from {{cookiecutter.app_name}}.app import create_app from {{cookiecutter.app_name}}.app import create_app
from {{cookiecutter.app_name}}.settings import ProdConfig, DevConfig from {{cookiecutter.app_name}}.settings import ProdConfig, DevConfig
def test_production_config(): def test_production_config():
app = create_app(ProdConfig) app = create_app(ProdConfig)
assert app.config['ENV'] == 'prod' assert app.config['ENV'] == 'prod'

@ -5,6 +5,7 @@ from {{cookiecutter.app_name}}.public.forms import LoginForm
from {{cookiecutter.app_name}}.user.forms import RegisterForm from {{cookiecutter.app_name}}.user.forms import RegisterForm
from .factories import UserFactory from .factories import UserFactory
class TestRegisterForm: class TestRegisterForm:
def test_validate_user_already_registered(self, user): def test_validate_user_already_registered(self, user):

@ -7,6 +7,7 @@ import pytest
from {{ cookiecutter.app_name }}.user.models import User, Role from {{ cookiecutter.app_name }}.user.models import User, Role
from .factories import UserFactory from .factories import UserFactory
@pytest.mark.usefixtures('db') @pytest.mark.usefixtures('db')
class TestUser: class TestUser:

@ -1,5 +1,5 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
'''The app module, containing the app factory function.''' """The app module, containing the app factory function."""
from flask import Flask, render_template from flask import Flask, render_template
from {{cookiecutter.app_name}}.settings import ProdConfig from {{cookiecutter.app_name}}.settings import ProdConfig
@ -16,11 +16,11 @@ from {{cookiecutter.app_name}} import public, user
def create_app(config_object=ProdConfig): def create_app(config_object=ProdConfig):
'''An application factory, as explained here: """An application factory, as explained here:
http://flask.pocoo.org/docs/patterns/appfactories/ http://flask.pocoo.org/docs/patterns/appfactories/
:param config_object: The configuration object to use. :param config_object: The configuration object to use.
''' """
app = Flask(__name__) app = Flask(__name__)
app.config.from_object(config_object) app.config.from_object(config_object)
register_extensions(app) register_extensions(app)

@ -11,6 +11,7 @@ from .compat import basestring
Column = db.Column Column = db.Column
relationship = relationship relationship = relationship
class CRUDMixin(object): class CRUDMixin(object):
"""Mixin that adds convenience methods for CRUD (create, read, update, delete) """Mixin that adds convenience methods for CRUD (create, read, update, delete)
operations. operations.
@ -44,6 +45,7 @@ class Model(CRUDMixin, db.Model):
"""Base model class that includes CRUD convenience methods.""" """Base model class that includes CRUD convenience methods."""
__abstract__ = True __abstract__ = True
# From Mike Bayer's "Building the app" talk # From Mike Bayer's "Building the app" talk
# https://speakerdeck.com/zzzeek/building-the-app # https://speakerdeck.com/zzzeek/building-the-app
class SurrogatePK(object): class SurrogatePK(object):

@ -1,4 +1,4 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
'''The public module, including the homepage and user auth.''' """The public module, including the homepage and user auth."""
from . import views from . import views

@ -1,9 +1,11 @@
# -*- coding: utf-8 -*-
from flask_wtf import Form from flask_wtf import Form
from wtforms import TextField, PasswordField from wtforms import TextField, PasswordField
from wtforms.validators import DataRequired from wtforms.validators import DataRequired
from {{cookiecutter.app_name}}.user.models import User from {{cookiecutter.app_name}}.user.models import User
class LoginForm(Form): class LoginForm(Form):
username = TextField('Username', validators=[DataRequired()]) username = TextField('Username', validators=[DataRequired()])
password = PasswordField('Password', validators=[DataRequired()]) password = PasswordField('Password', validators=[DataRequired()])

@ -1,5 +1,5 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
'''Public section, including homepage and signup.''' """Public section, including homepage and signup."""
from flask import (Blueprint, request, render_template, flash, url_for, from flask import (Blueprint, request, render_template, flash, url_for,
redirect, session) redirect, session)
from flask.ext.login import login_user, login_required, logout_user from flask.ext.login import login_user, login_required, logout_user
@ -13,6 +13,7 @@ from {{cookiecutter.app_name}}.database import db
blueprint = Blueprint('public', __name__, static_folder="../static") blueprint = Blueprint('public', __name__, static_folder="../static")
@login_manager.user_loader @login_manager.user_loader
def load_user(id): def load_user(id):
return User.get_by_id(int(id)) return User.get_by_id(int(id))
@ -32,6 +33,7 @@ def home():
flash_errors(form) flash_errors(form)
return render_template("public/home.html", form=form) return render_template("public/home.html", form=form)
@blueprint.route('/logout/') @blueprint.route('/logout/')
@login_required @login_required
def logout(): def logout():
@ -39,6 +41,7 @@ def logout():
flash('You are logged out.', 'info') flash('You are logged out.', 'info')
return redirect(url_for('public.home')) return redirect(url_for('public.home'))
@blueprint.route("/register/", methods=['GET', 'POST']) @blueprint.route("/register/", methods=['GET', 'POST'])
def register(): def register():
form = RegisterForm(request.form, csrf_enabled=False) form = RegisterForm(request.form, csrf_enabled=False)
@ -53,6 +56,7 @@ def register():
flash_errors(form) flash_errors(form)
return render_template('public/register.html', form=form) return render_template('public/register.html', form=form)
@blueprint.route("/about/") @blueprint.route("/about/")
def about(): def about():
form = LoginForm(request.form) form = LoginForm(request.form)

@ -3,6 +3,7 @@ import os
os_env = os.environ os_env = os.environ
class Config(object): class Config(object):
SECRET_KEY = os_env.get('{{cookiecutter.app_name | upper}}_SECRET', 'secret-key') # TODO: Change me SECRET_KEY = os_env.get('{{cookiecutter.app_name | upper}}_SECRET', 'secret-key') # TODO: Change me
APP_DIR = os.path.abspath(os.path.dirname(__file__)) # This directory APP_DIR = os.path.abspath(os.path.dirname(__file__)) # This directory

@ -1,3 +1,3 @@
'''The user module.''' # -*- coding: utf-8 -*-
"""The user module."""
from . import views from . import views

@ -1,9 +1,11 @@
# -*- coding: utf-8 -*-
from flask_wtf import Form from flask_wtf import Form
from wtforms import TextField, PasswordField from wtforms import TextField, PasswordField
from wtforms.validators import DataRequired, Email, EqualTo, Length from wtforms.validators import DataRequired, Email, EqualTo, Length
from .models import User from .models import User
class RegisterForm(Form): class RegisterForm(Form):
username = TextField('Username', username = TextField('Username',
validators=[DataRequired(), Length(min=3, max=25)]) validators=[DataRequired(), Length(min=3, max=25)])

@ -26,6 +26,7 @@ class Role(SurrogatePK, Model):
def __repr__(self): def __repr__(self):
return '<Role({name})>'.format(name=self.name) return '<Role({name})>'.format(name=self.name)
class User(UserMixin, SurrogatePK, Model): class User(UserMixin, SurrogatePK, Model):
__tablename__ = 'users' __tablename__ = 'users'

@ -1,9 +1,10 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
'''Helper utilities and decorators.''' """Helper utilities and decorators."""
from flask import flash from flask import flash
def flash_errors(form, category="warning"): def flash_errors(form, category="warning"):
'''Flash all errors for a form.''' """Flash all errors for a form."""
for field, errors in form.errors.items(): for field, errors in form.errors.items():
for error in errors: for error in errors:
flash("{0} - {1}" flash("{0} - {1}"

Loading…
Cancel
Save