Django 信号、中间件、i18n 专题
信号
Django中提供了“信号调度”,用于在框架执行操作时解耦。通俗来讲,就是一些动作发生的时候,信号允许特定的发送者去提醒一些接受者。
1. Django内置信号
Model signals pre_init # django的modal执行其构造方法前,自动触发 post_init # django的modal执行其构造方法后,自动触发 pre_save # django的modal对象保存前,自动触发 post_save # django的modal对象保存后,自动触发 pre_delete # django的modal对象删除前,自动触发 post_delete # django的modal对象删除后,自动触发 m2m_changed # django的modal中使用m2m字段操作第三张表(add,remove,clear)前后,自动触发 class_prepared # 程序启动时,检测已注册的app中modal类,对于每一个类,自动触发 Management signals pre_migrate # 执行migrate命令前,自动触发 post_migrate # 执行migrate命令后,自动触发 Request/response signals request_started # 请求到来前,自动触发 request_finished # 请求结束后,自动触发 got_request_exception # 请求异常后,自动触发 Test signals setting_changed # 使用test测试修改配置文件时,自动触发 template_rendered # 使用test测试渲染模板时,自动触发 Database Wrappers connection_created # 创建数据库连接时,自动触发
from django.core.signals import request_finished from django.core.signals import request_started from django.core.signals import got_request_exception from django.db.models.signals import class_prepared from django.db.models.signals import pre_init, post_init from django.db.models.signals import pre_save, post_save from django.db.models.signals import pre_delete, post_delete from django.db.models.signals import m2m_changed from django.db.models.signals import pre_migrate, post_migrate from django.test.signals import setting_changed from django.test.signals import template_rendered from django.db.backends.signals import connection_created def callback(sender, **kwargs): print("xx_callback") print(sender,kwargs) xx.connect(callback) # xx指上述导入的内容
from django.core.signals import request_finished from django.dispatch import receiver @receiver(request_finished) def my_callback(sender, **kwargs): print("Request finished!")
2. 自定义信号
a. 定义信号
import django.dispatch pizza_done = django.dispatch.Signal(providing_args=["toppings", "size"])
b. 注册信号
def callback(sender, **kwargs): print("callback") print(sender,kwargs) pizza_done.connect(callback)
c. 触发信号
from 路径 import pizza_done pizza_done.send(sender='Jonathan',toppings=123, size=456)
于内置信号的触发者已经集成到Django中,所以其会自动调用,而对于自定义信号则需要开发者在任意位置触发。
Middleware
待续
i18n
待续
Django settings
""" 更多信息参考: https://docs.djangoproject.com/en/1.11/topics/settings/ https://docs.djangoproject.com/en/1.11/ref/settings/ """ import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/ # 对称加密中会用到 SECRET_KEY = ')rt1ka2wqqv%%#!+x9pezqkn!r#!3)+%cee1l4fz$0!s--*!#1' DEBUG = True # 开发者模式,生产环境时 DEBUG=False ALLOWED_HOSTS = ['*'] # 访问主机,生产环境部署时需设置 APPEND_SLASH = True # url,自动补齐 / # 实现app可插拔 INSTALLED_APPS = [ # ....... 'polls', 'bootstrap3', ] # 中间件配置,有顺序 MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'mysite.urls' # 根url # 前端模板配置 TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', # 'BACKEND': 'django.template.backends.jinja2.Jinja2, # 搜索引擎配置 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'context_processors.global_setting', # 自定义全局变量 ], }, }, ] WSGI_APPLICATION = 'mysite.wsgi.application' # 设置数据库 # https://docs.djangoproject.com/en/1.11/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # 缓存 CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.db.DatabaseCache', 'LOCATION': 'my_cache_table', # 数据库表 } } # Password validation # https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/1.11/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # 邮箱配置 EMAIL_HOST = 'smtp.126.com' EMAIL_PORT = 25 EMAIL_HOST_USER = '******' EMAIL_HOST_PASSWORD = '******' # EMAIL_USE_SSL = True # if port is 587, set True # EMAIL_USE_TLS = True # if port is 465, set True # 翻译文件路径 LOCALE_PATH = [os.path.join(BASE_DIR, 'locale')] # 数据库之类的初始数据 FIXTURE_DIRS = os.path.join(BASE_DIR, 'fixture') # 日志配置 LOGGING = { 'version':1, 'handlers':{ 'null':{}, 'console':{}, 'file':{}, 'ansible_logs':{}, }, } # 用户上传的静态文件 MEDIA_ROOT = os.path.join(BASE_DIR, 'mdia') MEDIA_URL = '/media' # Auth LOGIN_URL = '/account/login' # 设置默认登录页面 AUTH_USER_MODEL = 'auth.user' # 设置用户验证的库表 LOGIN_REDIRECT = '/' # 如果没有?next=,登录后的跳转网页 AUTHENTICATION_BACKENDS = ['django.contrib.auth.backends.ModelBackend'] # 如LDAP认证可重写ModelBacken;依次认证 LOGOUT_REDIRECT_URL = None # 登录出,重定向页面 # Sessions SESSION_COOKIE_AGE = 1209600 SESSION_COOKIE_DOMAIN = None # session 只在当前域名下有效 SESSION_COOKIE_NAME = 'sessionid' SESSION_COOKIE_PATH = '/' # 所有页面有效 SESSION_COOKIE_ENGINE = 'django.contib.sessions.backends.db' SESSION_EXPIRE_AT_BROWSER_CLOSE = False # 默认浏览器关闭session不失效 # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.11/howto/static-files/ # STATIC_ROOT = r'/www/example/com/staic' STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ]
posted on 2017-10-18 10:57 Jonathan1314 阅读(353) 评论(0) 编辑 收藏 举报