[Django1.5] two-scoops-django-best-practices 读书笔记

来源:互联网 发布:淘宝今天业绩 编辑:程序博客网 时间:2024/06/05 11:23

[Django1.5] two-scoops-django-best-practices 读书笔记


说明:本文由@易枭寒(Email:yixiaohan121318@gmail.com   QQ:499065469)搜索整理,转载请注明出处,和作者信息。



Coding Style--代码风格


1、The Importance of Making Your Code Readable

Avoid abbreviating variable names. 避免变量名缩写Write out your function argument names.  写方法的参数名Document your classes and methods.  文档注释Refactor repeated lines of code into reusable functions or methods  重构(可重用)




2、PEP8 代码规范

“Use 4 spaces per indentation level.” 每个缩进之间四个空格“Separate top-level function and class definitions with two blank lines.”  顶层方法与类定义之间用两个空行“Method definitions inside a class are separated by a single blank line.” 类内的方法与类之间 用一个空行



3、The Word on Imports
PEP 8 suggests that imports should be grouped in the following order:
1. Standard library imports2. Related third-party imports3. Local application or library speci$c imports


例子:

# Stdlib imports 标准库from math import sqrtfrom os.path import abspath# Core Django imports  Djangofrom django.db import modelsfrom django.utils.translation import ugettext_lazy as _# Third-party app imports 第三方from django_extensions.db.models import TimeStampedModel# Imports from your apps 自己写得appfrom splits.models import BananaSplit

the import order here is:
1. Standard library imports.
2. Imports from core Django.
3. Imports from third-party apps.
4. Imports from the apps that you created as part of your Django project. 



4、Use Relative Imports  使用相对 import

对于app模块类导入,不要使用硬编码,而是要使用相对命名空间导入


your cones  app contains hardcoded imports, which are bad!  硬编码,这是坏习惯。

# cones/views.py# Hard coding of package namefrom django.views.generic import CreateView# DON’T DO THIS: Hardcoding of the 'cones' packagefrom cones.models import WaffleConefrom cones.forms import WaffleConeFormclass WaffleConeCreateView(CreateView):    model = WaffleCone    form_class = WaffleConeForm

正确的做法:

# cones/views.pyfrom django.views.generic import CreateView# Hard coding of the 'cones' packagefrom .models import WaffleConefrom .forms import WaffleConeFormclass WaffleConeCreateView(CreateView):    model = WaffleCone    form_class = WaffleConeForm

5、Avoid Using Import * 避免使用 import *


6、好的习惯:

Use  underscores  (the ‘_’ character)  in  URL pattern  names  rather than  dashes. Note that we  are  referring to the  name argument of url()  here, not the  actual URL typed into the browser. Dashes in actual URLs are  fine.Use underscores rather than dashes in template block names.

7、Never Code to the IDE (or Text Editor)

Another way  of saying “Never  code  to  the IDE” could  also  be “Coding by  Convention”  不要使用IDE推荐的代码格式化工具或IDE的编程风格,而是要使用自己的(PEP8)编码风格。