django settings.py 配置文件


#coding=utf-8
import os
DEBUG = True
TEMPLATE_DEBUG = DEBUG

APP_PATH = os.path.split(__file__)[0]
ROOT_PATH = os.path.split(APP_PATH)[0]

ADMINS = (
    # ('Your Name', 'your_email@example.com'),
)

SVN = ''
MANAGERS = ADMINS


#email config
EMAIL_HOST = 'xx@163.com'
EMAIL_PORT = 88
EMAIL_HOST_USER = 'xxuser@163.coom'
EMAIL_HOST_PASSWORD = "china@10086"


# 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 = 'zh-cn'

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 = APP_PATH + os.sep + "media"

# 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 = '/media'
#静态文件防止发布的时候,浏览器还缓存可以设置 MEDIA_URL = "/svnNum/media/" 这样每次更新的时候,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 = ''

# 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/'

LOGIN_REDIRECT_URL = 'index/'
# Additional locations of static files
STATICFILES_DIRS = (
    # 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 = 'xxxxxxxxxxxxx'

# 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',
)
#全局参数处理器,默认setting是没有的这个配置的,用户可以用户自定义全局参数,参考如下:
#http://stackoverflow.com/questions/7470179/module-django-core-context-processors-does-not#-define-a-auth-callable-reques
TEMPLATE_CONTEXT_PROCESSORS = (
    "django.contrib.auth.context_processors.auth",
    "django.core.context_processors.media",   
    "django.core.context_processors.request",
)   

#中间件,用户也可以自己定义中间件,用于拦截功能,如匿名用户不可以进入某一路径等。
#注意中间件的位置先后顺序。创建一个中间件,并重写process_request该方法。就可以创建一个中间#件了
MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'myproject.myMiddlewareFileNAME.myMiddlewareClass',
    #'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.gzip.GZipMiddleware',
)

ROOT_URLCONF = 'myapp.urls'

TEMPLATE_DIRS = (
    APP_PATH + os.sep + 'templates',
    # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
)
#创建自己的后台用户
AUTHENTICATION_BACKENDS = (
    'myapp.authBackend.MyBackend',
)

#自定义过滤器时,要在这添加配置
INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'myproject.myapp',##<------在这
)

#memcache作为后台缓存引擎
mcs=MemCacheSettings.getSettings()
CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
        'LOCATION': 'ip:port',
        'TIMEOUT': 24*60*60  #24小时有效
    }
}

SESSION_COOKIE_NAME="session_id"
SESSION_ENGINE = 'django.contrib.sessions.backends.cache'
#设置浏览器关闭时默认就是False,session也有效,SESSION_COOKIE_AGE设置的时间
SESSION_EXPIRE_AT_BROWSER_CLOSE = False 
SESSION_COOKIE_AGE = 86400 #24小时有效
SESSION_SAVE_EVERY_REQUEST = True

LOGGING = xx



自定义中间件


#coding=utf-8

from django.contrib import auth
from django.utils.functional import SimpleLazyObject
from django.http import HttpResponseRedirect
from threading import local

def get_user(request):
    if not hasattr(request, '_cached_user'):
        request._cached_user = auth.get_user(request)
    return request._cached_user



class AuthenticationMiddleware(object):
    
    def _anonymousUserAllowPath(self, path):
        "匿名用户可否进入某路径"
        allowPathList = []
        for allowPath in allowPathList:
            if path.find(allowPath) == 0: return True
        
        return False
    
    
    def process_request(self, request):
        assert hasattr(request, 'session'), "The Django authentication middleware requires session middleware to be installed. Edit your MIDDLEWARE_CLASSES setting to insert 'django.contrib.sessions.middleware.SessionMiddleware'."

        u = request.user = SimpleLazyObject(lambda: get_user(request))
        #userType = UserLocal.getUserType()
        userType = request.session.get('userType', None)
 
        if u and str(u) != "AnonymousUser":
            setUser(u)


3、自定义后台

#coding=utf-8

from threading import local

_userLocal = local()

class User(object):
    """
   符合django的用户要求,如一些django要的字段,如last_login、is_active、is_authenticated、save等
    """
    def __init__(self, username, password):
        self.username = username
        self.password = password
        


class UserControl(object):
    
    @staticmethod
    def setUser(user=None):
        _userLocal.user = user
        
    @staticmethod
    def getUser():
        return getattr(_userLocal, 'user', None)
    
    
    @staticmethod
    def hasPermission(perm, user=None):
        return True
    
        
    @staticmethod
    def login(name, pwd):
        users = User.find({"_id":name, "password":pwd})
        if not users:
            raise Exception("Can't login with name:%s, pwd:%s" %(name, pwd))
        
        UserControl.setUser(users[0])

4、自定义过滤器

步骤:

一、与templates同一目录上创建一个templates目录

二、在settings.py文件的配置项INSTALLED_APPS中添加你这APP在里面。格式如下:myProject.myApp

三、在templates目录下随便创建一个.py文件如:

#coding=utf-8
import time
from django import template
import time

register = template.Library()


@register.filter(name='cut')
def cut(value, arg):
    return value.replace(arg, '')

@register.filter
def lower(value):
    return value.lower()




  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值