Django in Action: Coding Style

Django in Action: Coding Style

Python Coding Style (Simple)

  • 代码缩进优先使用空格 <space> 而不是制表符 tab

  • 需要换行的时候,在二元运算符之前换行:

    1
    2
    3
    4
    5
    6
    7
    8
    # wrong
    inventory = warehouse_a +
    warehouse_b +
    warehouse_c
    # right
    inventory = warehouse_a
    + warehouse_b
    + warehouse_c
  • 引入多个库时分开写 importfrom ... import ... 可以写在一行

  • ……

详见 PEP8Google Python Style

Django Coding Style (Part)

  1. import 的顺序:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    # future 下一版本的新特性
    from __future__ import print_funtion

    # standard library 标准库
    import os
    import sys
    from itertools import chain

    # third-party 第三方库
    import chardet

    # Django
    from django.http import HttpResponseRedirct
    from django.http.response import (
    Http404, HttpResponse, HttpResponseNotAllowed, StreamingHttpResponse,
    cookie,
    )

    # local 本地模块
    from .models import StudentClass

    # try/except
    try:
    import yaml
    except ImportError:
    yaml = None

    CONSTANT = 'foo'
  2. 模板变量的风格

    1
    2
    3
    4
    5
    # wrong
    {{foo}}

    #right
    {{ foo }}
  3. views.py 视图函数的参数:第一个参数命名为 request

    1
    def index(request, ...): ...
  4. ……

完整 Django Coding Style:https://docs.djangoproject.com/en/dev/internals/contributing/writing-code/coding-style/