django複数のデータベースに接続し、redisを構成し、jinja 2テンプレートエンジンを交換します.
8553 ワード
djangoでは、複数のデータベースを使用します.
1.プロジェクトフォルダにdatabaseを作成するrouter.pyファイル、内容は以下の通りです.
2.DATABASES形式の設定は以下の通りです.
3.DATABASE_の設定ROUTERS,DATABASE_APPS_MAPPING :
djangoではjinja 2テンプレートエンジンを使用します.
1.django-jinjaプラグインをインストールします.2.アクセスカード:settingに書き込む:INSTALLED_APPS+=('django_jinja')テンプレートエンジンを構成します.
テンプレートのいくつかの使用方法:
djangoでredisキャッシュを するには:
プロジェクトのsettingsでの :
アプリのviewsには:
1.プロジェクトフォルダにdatabaseを作成するrouter.pyファイル、内容は以下の通りです.
# -*- coding: utf-8 -*-
from django.conf import settings
DATABASE_MAPPING = settings.DATABASE_APPS_MAPPING
class DatabaseAppsRouter(object):
"""
A router to control all database operations on models for different
databases.
In case an app is not set in settings.DATABASE_APPS_MAPPING, the router
will fallback to the `default` database.
Settings example:
DATABASE_APPS_MAPPING = {'app1': 'db1', 'app2': 'db2'}
"""
def db_for_read(self, model, **hints):
""""Point all read operations to the specific database."""
if model._meta.app_label in DATABASE_MAPPING:
return DATABASE_MAPPING[model._meta.app_label]
return None
def db_for_write(self, model, **hints):
"""Point all write operations to the specific database."""
if model._meta.app_label in DATABASE_MAPPING:
return DATABASE_MAPPING[model._meta.app_label]
return None
def allow_relation(self, obj1, obj2, **hints):
"""Allow any relation between apps that use the same database."""
db_obj1 = DATABASE_MAPPING.get(obj1._meta.app_label)
db_obj2 = DATABASE_MAPPING.get(obj2._meta.app_label)
if db_obj1 and db_obj2:
if db_obj1 == db_obj2:
return True
else:
return False
return None
# for Django 1.4 - Django 1.6
def allow_syncdb(self, db, model):
"""Make sure that apps only appear in the related database."""
if db in DATABASE_MAPPING.values():
return DATABASE_MAPPING.get(model._meta.app_label) == db
elif model._meta.app_label in DATABASE_MAPPING:
return False
return None
# Django 1.7 - Django 1.11
def allow_migrate(self, db, app_label, model_name=None, **hints):
print db, app_label, model_name, hints
if db in DATABASE_MAPPING.values():
return DATABASE_MAPPING.get(app_label) == db
elif app_label in DATABASE_MAPPING:
return False
return None
2.DATABASES形式の設定は以下の通りです.
DATABASES = {
'default': {
'ENGINE': 'sqlserver',
'NAME': 'db1',
'HOST': 'xxx.xxx.xx.xxx',
'PORT': xxxx,
'USER': 'xxxx',
'PASSWORD': 'xxxx',
},
'db1': {
'ENGINE': 'sqlserver',
'NAME': 'db2',
'HOST': 'xxx.xxx.xx.xxx',
'PORT': xxxx,
'USER': 'xxxx',
'PASSWORD': 'xxxx',
}
}
3.DATABASE_の設定ROUTERS,DATABASE_APPS_MAPPING :
DATABASE_ROUTERS = ['project_name.database_router.DatabaseAppsRouter']
DATABASE_APPS_MAPPING = {
'app': 'db1',
}
djangoではjinja 2テンプレートエンジンを使用します.
1.django-jinjaプラグインをインストールします.2.アクセスカード:settingに書き込む:INSTALLED_APPS+=('django_jinja')テンプレートエンジンを構成します.
TEMPLATES = [
{
"BACKEND": "django_jinja.backend.Jinja2",
"APP_DIRS": True,
'DIRS': [os.path.join(BASE_DIR, 'templates')],
"OPTIONS": {
# Match the template names ending in .html but not the ones in the admin folder.
"match_extension": ".html",
"match_regex": r"^(?!admin/).*",
"app_dirname": "templates",
# Can be set to "jinja2.Undefined" or any other subclass.
"undefined": None,
"newstyle_gettext": True,
# !!! reverse URL
'globals': {
'reverse': 'django.core.urlresolvers.reverse',
# 'auth_url': 'utils.tool.auth_url',
},
"context_processors": [
"django.contrib.auth.context_processors.auth",
"django.template.context_processors.debug",
"django.template.context_processors.i18n",
"django.template.context_processors.media",
"django.template.context_processors.static",
"django.template.context_processors.tz",
"django.contrib.messages.context_processors.messages",
],
"extensions": [
"jinja2.ext.do",
"jinja2.ext.loopcontrols",
"jinja2.ext.with_",
"jinja2.ext.i18n",
"jinja2.ext.autoescape",
"django_jinja.builtins.extensions.CsrfExtension",
"django_jinja.builtins.extensions.CacheExtension",
"django_jinja.builtins.extensions.TimezoneExtension",
"django_jinja.builtins.extensions.UrlsExtension",
"django_jinja.builtins.extensions.StaticFilesExtension",
"django_jinja.builtins.extensions.DjangoFiltersExtension",
],
"bytecode_cache": {
"name": "default",
"backend": "django_jinja.cache.BytecodeCache",
"enabled": False,
},
"autoescape": True,
"auto_reload": DEBUG,
"translation_engine": "django.utils.translation",
}
},
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'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',
],
},
},
]
テンプレートのいくつかの使用方法:
#### a href django urls !
!
djangoでredisキャッシュを するには:
プロジェクトのsettingsでの :
CACHES = {
"default": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": "redis://127.0.0.1:6379/0",
# "redis://127.0.0.1:6379/2", redis ( ) redis
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
"PARSER_CLASS": "redis.connection.HiredisParser",
# "PICKLE_VERSION": -1, # PICKLE_VERSION ,
# "PASSWORD": "mysecret" # ,
# "SOCKET_CONNECT_TIMEOUT": 5, # in seconds
# "SOCKET_TIMEOUT": 5, # in seconds
# "COMPRESSOR": "django_redis.compressors.zlib.ZlibCompressor", # django-redis ,
# "CONNECTION_POOL_KWARGS": {"max_connections": 100} #
# :
# from django.core.cache import get_cache
# from django_redis import get_redis_connection
#
# r = get_redis_connection("default") # Use the name you have defined for Redis in settings.CACHES
# connection_pool = r.connection_pool
# print("Created connections so far: %d" % connection_pool._created_connections)
}
}
}
アプリのviewsには:
from django.core.cache.backends.base import DEFAULT_TIMEOUT
from django.core.cache import cache
from django.views.decorators.cache import cache_page
:
cache.set('key1','twy', 600)
value = cache.get('key1')
@cache_page(60 * 15): , , , ,