ikeikeikeike's unk blog.

http://github-awards.com/users/ikeikeikeike

どーしてもPEP8を守れない人用のDjango1.7の設定

以下ネタです。基本的にPEP8は準拠しませう
また使用しているDjango1.7の新機能Applications, System check frameworkの使用方法は全くもって正しくないので真似しないで下さい

Django1.7おめでとうございます!!!

Django1.7がリリースしてめでたかったので新しく1.7から追加された機能ApplicationsとSystem check frameworkの仕組みを利用して強制的にPEP8を守らしてみました。

まずDjangoのappをつくりましょう。checkpep8でよいですかね?

$ python manage.py startapp checkpep8

出来上がったcheckpep8アプリの__init__.pyにdefault_app_configを追加

checkpep8/__init__.py

default_app_config = 'checkpep8.apps.Checkpep8Config'

apps.pyを作成、下記の内容を書いておく(予めsettingsにはcheckpep8を登録しておきましょう)

checkpep8/apps.py

import sys
import pep8
from cStringIO import StringIO

from django import apps
from django.core import checks
from django.conf import settings
from django.utils.translation import ugettext_lazy as _


def capture(func, *args, **kwargs):
    out, sys.stdout = sys.stdout, StringIO()
    func(*args, **kwargs)
    sys.stdout.seek(0)
    res = sys.stdout.read()
    sys.stdout = out
    return res


def checker(**kwargs):
    app_names = (
        app_name for
        app_name in settings.INSTALLED_APPS
        if not app_name.startswith('django')
    )

    app_paths = [
        apps.AppConfig.create(app_name).path
        for app_name in app_names
    ]

    errors = []

    outs = capture(pep8.StyleGuide().check_files, app_paths)
    for out in outs.splitlines():
        errors.append(
            checks.Error(
                out,
                hint=None,
                obj=None,
                id='pep8.%s' % out.split(' ')[1],
            )
        )

    return errors


class Checkpep8Config(apps.AppConfig):
    name = 'checkpep8'
    verbose_name = _("Checkpep8")

    def ready(self):
        checks.register('pep8')(checker)

pep8に引っかかるようにcheckpep8/models.pyを編集

from django.db import models


class First(models.Model):

    def pep(self):
        return


    def too_many_blank_linespep(self):
        return

現在のProjectの状態

$ tree
.
├── checkpep8
│   ├── __init__.py
│   ├── admin.py
│   ├── apps.py
│   ├── models.py
│   ├── tests.py
│   ├── urls.py
│   └── views.py
├── manage.py
└── runserver_pep8
    ├── __init__.py
    ├── settings.py
    ├── urls.py
    └── wsgi.py

いざmakemigrations

$ python manage.py makemigrations checkpep8
CommandError: System check identified some issues:

ERRORS:
?: (pep8.E303) /Users/ikeda/.virtualenvs/django17/blog/runserver_pep8/checkpep8/models.py:13:5: E303 too many blank lines (3)

やりました!! System check framework が効いている。。。 pep8チェックで makemigrations 動かない!!

models.pyを直してみる

from django.db import models


class First(models.Model):

    def pep(self):
        return

    def too_many_blank_linespep(self):
        return

再度 makemigration

$ python manage.py makemigrations checkpep8
Migrations for 'checkpep8':
  0001_initial.py:
    - Create model First

おおお、makemigrationsがうごいたー

これでpep8準拠てか、強制の方向へ。。だれかautopep8でも試してみてください〜。