美文网首页
django连接多个数据库,配置redis,更换jinja2模板

django连接多个数据库,配置redis,更换jinja2模板

作者: 都江堰古巨基 | 来源:发表于2018-01-23 15:57 被阅读0次

    django中使用多个数据库:

    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中使用jinja2模板引擎:

    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',
                ],
            },
        },
    ]
    

    在模板中的一些用法:

    <link rel="stylesheet" href="{{ static("css/bootstrap.css") }}" type="text/css" />
    <script type="text/javascript" src="{{ static("js/jquery-3.2.1.min.js") }}"></script>
    #### 这个a标签的href是django中urls里面的!
    <a href="{{ reverse('test') }}" class="btn btn-danger">点我提示!</a>
    

    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)
            }
        }
    }
    

    APP的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):缓存整个界面,即装饰器之后的整个方法,但有个问题,改动了方法之后,数据只有等缓存过期了才会更新
    

    相关文章

      网友评论

          本文标题:django连接多个数据库,配置redis,更换jinja2模板

          本文链接:https://www.haomeiwen.com/subject/ffbsaxtx.html