Django1.3 使用心得

一、django项目结构

一般常见django项目目录机构如下图:


二、创建django project

windows环境下,进入命令行运行窗口,在项目所在的目录下,使用django-admin/python manage.py进行django项目的创建/管理。

Step1.

    使用django-admin startproject yourproject命令创建,成功执行后根目录下会生成settings.py,urls.py,manage.py

    settings.py中需更改项目所需的数据库参数

Step2.

    使用python manage.py startapp yourapp,可以创建多个app

Step3.

    使用python manage.py syncdb 在数据库中创建与models.py代码对应的表,如果没有,则默认生产django依赖的相关表。

    使用python manage.py inspectdb > yourproject/db/models.py 根据数据库反向生成models.py。

    使用python manage.py runserver 8008启动项目

三、实战项目

    1.settings.py配置解析
 
 
# -*- coding:utf-8 -*-
# Django settings for NYPayment project.
from config import *
#设置为True则会返回django的错误页面
DEBUG = False #是否开启debug,生产环境设置为
TEMPLATE_DEBUG = False #是否开启debug,生产环境设置为False

ADMINS = (
    # ('Your Name', '[email protected]'),
)

MANAGERS = ADMINS
#以下所有数据库相关参数都从config.py中引入
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': db_name,                      # Or path to database file if using sqlite3.
        'USER': db_user,                      # Not used with sqlite3.
        'PASSWORD': db_password,                  # Not used with sqlite3.
        'HOST': db_host,                      # Set to empty string for localhost. Not used with sqlite3.
        'PORT': db_port,                      # Set to empty string for default. Not used with sqlite3.
    }
}

# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# On Unix systems, a value of None will cause Django to use the same
# timezone as the operating system.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'Asia/Shanghai'

# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us' #可以用于做国际化参数设置,这里不做赘述。

SITE_ID = 1

# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True #开启支持国际化
 
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale
USE_L10N = True

# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = '' #可用于配置上传文件的根目录

# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = '' #访问上传文件的url

# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = '' #静态文件的根目录,这里设置为空。实际生产环境中为了性能可能不放置在项目中,由apache指定

# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'

# URL prefix for admin static files -- CSS, JavaScript and images.
# Make sure to use a trailing slash.
# Examples: "http://foo.com/static/admin/", "/static/admin/".
ADMIN_MEDIA_PREFIX = '/static/admin/'
# Additional locations of static files

STATICFILES_DIRS = (#project_path+'/static/' 

 # Put strings here, like "/home/html/static" or "C:/www/django/static". 

 # Always use forward slashes, even on Windows. 

 # Don't forget to use absolute paths, not relative paths.

)

# List of finder classes that know how to find static files in

# various locations.

STATICFILES_FINDERS = ( 

 'django.contrib.staticfiles.finders.FileSystemFinder', 

 'django.contrib.staticfiles.finders.AppDirectoriesFinder',

# 'django.contrib.staticfiles.finders.DefaultStorageFinder',

)

# Make this unique, and don't share it with anybody.

SECRET_KEY = 'nr+l!-c%9vi2=!z-#a2&f#^t#qzyy&-__xu7l3&p9c-9^am%8n'

# List of callables that know how to import templates from various sources.

TEMPLATE_LOADERS = ( 

 'django.template.loaders.filesystem.Loader', 

 'django.template.loaders.app_directories.Loader',

# 'django.template.loaders.eggs.Loader',

)

MIDDLEWARE_CLASSES = ( 

 'django.middleware.common.CommonMiddleware', 

 'django.contrib.sessions.middleware.SessionMiddleware', 

 # 'django.middleware.csrf.CsrfViewMiddleware',#用于防御跨站点请求伪造全局中间件,在这个项目中不需要。 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware',

)

ROOT_URLCONF = 'front_web.urls'

TEMPLATE_DIRS = (os.path.join(os.path.dirname(__file__), 'templates').replace('\\','/'),)

INSTALLED_APPS = ( 

 'django.contrib.auth', 

 'django.contrib.contenttypes', 

 'django.contrib.sessions', 

 'django.contrib.sites', 

 'django.contrib.messages', 

 'django.contrib.staticfiles', 

 # Uncomment the next line to enable the admin: 'django.contrib.admin', 

 # Uncomment the next line to enable admin documentation: 

 # 'django.contrib.admindocs', 

 'front_web.gateways',#install your app这里django会把你的app引入到工程中

)

CACHES = {#使用数据库方式缓存 

     'default': { 

         'BACKEND': 'django.core.cache.backends.db.DatabaseCache',

         'LOCATION': 'django_cache_table' #python manage.py createcachetable创建django自带的缓存表 

     }

}

# A sample logging configuration. The only tangible logging# performed by this configuration is to send an email to

# the site admins on every HTTP 500 error.

# See http://docs.djangoproject.com/en/dev/topics/logging for

# more details on how to customize your logging configuration.

import logginglogging.basicConfig(

#这里日志作用方式为全局,整个项目中所有的日志都会记录在log.txt,当然还可以设置不同级别日志,这里不做赘述。

 level = logging.DEBUG, 

 format = '%(asctime)s %(levelname)s %(module)s.%(funcName)s Line:%(lineno)d %(message)s', 

 filename = PROJECT_PATH + 'log.txt',

)

SIGNATURE = True #自定义全局变量,from django.conf import settings可以引用所有全局变量

2.urls.py解析

from django.conf.urls.defaults import patterns, include, url

# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    # Uncomment the next line to enable the admin:
    url(r'^admin/', include(admin.site.urls)),
    url(r'^remit/', include('front_web.gateways.urls')),#这里采用的方式引入了app中urls,所有app访问的路由地址都会以/remit/开头
)
# -*- coding:utf-8 -*-
from django.conf.urls.defaults import patterns, include, url
# App中的urls.py

urlpatterns = patterns('front_web.gateways',#App所在的django目录
    url(r'^payment/$','payment.payment'),#子功能模块方法
    url(r'^query/$','query.query'),
)

3.app功能模块解析

# -*- coding: utf-8 -*-

from front_web.utils.msgcheck import *
import time

#@为app所需的两个装饰器,@post_required类似django自带的login_required,@exception()则用于记录异常日志
@post_required
@exception()
def payment(request):
    return HttpResponse({"status":"OK"}) #具体的业务逻辑代码已经省略

四、django请求生命周期示意图





猜你喜欢

转载自blog.csdn.net/core_coder/article/details/80485681
今日推荐