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

[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 imports
2. Related third-party imports
3. Local application or library speci$c imports


例子:

# Stdlib imports 标准库
from math import sqrt
from os.path import abspath
# Core Django imports  Django
from django.db import models
from django.utils.translation import ugettext_lazy as _
# Third-party app imports 第三方
from django_extensions.db.models import TimeStampedModel
# Imports from your apps 自己写得app
from 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 name
from django.views.generic import CreateView
# DON’T DO THIS: Hardcoding of the 'cones' package
from cones.models import WaffleCone
from cones.forms import WaffleConeForm
class WaffleConeCreateView(CreateView):
    model = WaffleCone
    form_class = WaffleConeForm

正确的做法:

# cones/views.py
from django.views.generic import CreateView
# Hard coding of the 'cones' package
from .models import WaffleCone
from .forms import WaffleConeForm
class 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)编码风格。






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值