django学习(1)编写技巧

本文详细介绍了使用Django框架进行项目开发的最佳实践,包括代码风格、引用规范、数据库使用、配置管理等方面,并提供了项目结构示例及应用命名建议。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

从这本书

two-scoops-django-best-practices-1.5

抄过来的。


=========================第一章=============================

风格规范

https://www.python.org/dev/peps/pep-0008/

“Use 4 spaces per indentation level.”
“Separate top-level function and class de$nitions with two blank lines.”

“Method de$nitions inside a class are separated by a single blank line.” 


关于引用

  1. Standard library imports

  2. Related third-party imports

  3. Local application or library speci$c imports 


尽量使用相对路径引用:

from .models import WaffleCone
from .forms import WaffleConeForm
class WaffleConeCreateView(CreateView):
    model = WaffleCone
    form_class = WaffleConeForm

不许用import *

Never Code to the IDE (or Text Editor) 

==============第二章=======================

Use the Same Database Locally and in Production 

Use Pip and Virtualenv 

=======================第三章=======================

icratings_project/
    .gitignore
    Makefile
    docs/
    requirements.txt
    icratings/
        manage.py
        media/
        products/
        profiles/
        ratings/
        static/
        templates/
        icratings/
            __init__.py
            settings/
            urls.py
            wsgi.py
大概就是django的项目结构啦。

<repository_root>/
    <django_project_root>/
        <configuration_root>/

Whatever layout is chosen should bedocumented clearly. 

==================第四章==================

项目命名和各种app

Write programs that do one thing and do it well.’” 

A good, obvious app name makes the project easier tomaintain. 

Use valid, PEP-8-compliant, importable Python package names: short, all-lowercasenames without numbers, dashes, periods, spaces, or special characters. 

When In Doubt, Keep Apps Small 

============================第五章关于配置===============

All settings "les need to be version-controlled. 

Don’t repeat yourself. You should inherit from a base settings  rather than cutting-and-pasting from one to another. 


local_settings.py. you would repeat yourself  and  could go wrong when copying and others.

you should 

Instead of having one settings.py, with this setup you have a settings/ directorycontaining your settings. It will typically contain something like the following 

settings/
      __init__.py
      base.py
      local.py
      staging.py
      test.py
      production.py

and run shell like:

$ django-admin.py shell --settings=twoscoops.settings.local 

$ django-admin.py runserver --settings=twoscoops.settings.local
inheriate

# settings/dev_pydanny.py
from .local import *

Keep Secret Keys Out With Environment Variables 

as platform-as-a-service. 

.bashrc, .bash_profile, or .profile: 

export SOME_SECRET_KEY=1c3-cr3am-15-yummy
export AUDREY_FREEZER_KEY=y34h-r1ght-d0nt-t0uch-my-1c3-cr34m


Handling Missing Secret Key Exceptions 

# settings/base.py
import os
# Normally you should not import ANYTHING from Django directly
# into your settings, but ImproperlyConfigured is an exception.
from django.core.exceptions import ImproperlyConfigured
def get_env_variable(var_name):
    """ Get the environment variable or return exception """
    try:
        return os.environ[var_name]
    except KeyError:
        error_msg = "Set the %s env variable" % var_name
        raise ImproperlyConfigured(error_msg)
SOME_SECRET_KEY = get_env_variable("SOME_SECRET_KEY")
and you would get an exception when you has improbably configured.


Using Multiple Requirements Files 


按以下方式填写需求文件:

requirements/
    _base.txt
    local.txt
    staging.txt
    production.txt
每一个差不多是下面那样:

-r _base.txt # includes the _base.txt requirements file
coverage==3.6
django-discover-runner==0.2.2
django-debug-toolbar==0.9.4
然后按照以下方式安装:

$ pip install -r requirements/local.txt


never hardcode  paths in Django settings .  

you should try something like this:

# At the top of settings/base.py
from os.path import join, abspath, dirname
here = lambda *x: join(abspath(dirname(__file__)), *x)
PROJECT_ROOT = here("..", "..")
root = lambda *x: join(abspath(PROJECT_ROOT), *x)
# Configuring MEDIA_ROOT
MEDIA_ROOT = root('media')
# Configuring STATIC_ROOT
STATIC_ROOT = root('collected_static')
# Additional locations of static files
STATICFILES_DIRS = (
    root('assets'),
)
# Configuring TEMPLATE_DIRS
TEMPLATE_DIRS = (
    root('templates'),
)


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值