Пример #1
0
def JINJA_CONFIG():
    from django.conf import settings
    config = {
        'extensions': [
            'tower.template.i18n', 'caching.ext.cache',
            'jinja2.ext.autoescape', 'jinja2.ext.with_', 'jinja2.ext.do'
        ],
        'finalize':
        lambda x: x if x is not None else ''
    }

    if not settings.DEBUG:
        import jinja2
        from caching.base import cache
        if hasattr(cache, 'scheme') and 'memcached' in cache.scheme:
            # We're passing the _cache object directly to jinja because
            # Django can't store binary directly; it enforces unicode on it.
            # Details:
            #     http://jinja.pocoo.org/2/documentation/api#bytecode-cache
            # and in the errors you get when you try it the other way.
            bc = jinja2.MemcachedBytecodeCache(cache._cache,
                                               "%sj2:" % settings.CACHE_PREFIX)
            config['cache_size'] = -1  # Never clear the cache
            config['bytecode_cache'] = bc
    return config
Пример #2
0
def JINJA_CONFIG():
    import jinja2
    from django.conf import settings
    from django.core.cache.backends.memcached import MemcachedCache
    from django.core.cache import caches
    cache = caches['memcache']
    config = {
        'extensions': [
            'jinja2.ext.i18n', 'tower.template.i18n', 'jinja2.ext.with_',
            'jinja2.ext.loopcontrols', 'jinja2.ext.autoescape',
            'pipeline.templatetags.ext.PipelineExtension'
        ],
        'finalize':
        lambda x: x if x is not None else ''
    }
    if isinstance(cache, MemcachedCache) and not settings.DEBUG:
        # We're passing the _cache object directly to jinja because
        # Django can't store binary directly; it enforces unicode on it.
        # Details: http://jinja.pocoo.org/2/documentation/api#bytecode-cache
        # and in the errors you get when you try it the other way.
        bc = jinja2.MemcachedBytecodeCache(cache._cache,
                                           "%s:j2:" % settings.CACHE_PREFIX)
        config['cache_size'] = -1  # Never clear the cache
        config['bytecode_cache'] = bc
    return config
def create_jinja_environment(loader, locale=None):
    """Create proper jinja environment."""

    cache = None
    if CAN_USE_JINJA2_TEMPLATE_CACHE.value:
        prefix = 'jinja2:bytecode:%s:/' % models.MemcacheManager.get_namespace(
        )
        cache = jinja2.MemcachedBytecodeCache(
            models.MemcacheManager,
            timeout=models.DEFAULT_CACHE_TTL_SECS,
            prefix=prefix)

    jinja_environment = jinja2.Environment(autoescape=True,
                                           finalize=finalize,
                                           extensions=['jinja2.ext.i18n'],
                                           bytecode_cache=cache,
                                           loader=loader)

    jinja_environment.filters['js_string'] = js_string

    if locale:
        i18n.get_i18n().set_locale(locale)
        jinja_environment.install_gettext_translations(i18n)

    return jinja_environment
Пример #4
0
    def get_jinja_environ(self, dir_names):

        bytecode_cache = jinja2.MemcachedBytecodeCache(
                jinja_filters.MemcacheManagerWithTTL(60*60*12),
                prefix="jinja2/bytecode/")

        jinja_environment = jinja2.Environment(
            autoescape=True, finalize=jinja_filters.finalize,
            extensions=['jinja2.ext.i18n'],
            bytecode_cache=bytecode_cache,
            loader=VirtualFileSystemTemplateLoader(
                self, self._logical_home_folder, dir_names))
        jinja_environment.filters['js_string'] = jinja_filters.js_string

        return jinja_environment
Пример #5
0
    def get_jinja_environ(self, dir_names):
        """Configure the environment for Jinja templates."""
        physical_dir_names = []
        for dir_name in dir_names:
            physical_dir_names.append(self._logical_to_physical(dir_name))

        bytecode_cache = jinja2.MemcachedBytecodeCache(
                jinja_filters.MemcacheManagerWithTTL(60*60*12),
                prefix="jinja2/bytecode/")

        jinja_environment = jinja2.Environment(
            autoescape=True, finalize=jinja_filters.finalize,
            extensions=['jinja2.ext.i18n'],
            bytecode_cache=bytecode_cache,
            loader=jinja2.FileSystemLoader(physical_dir_names))
        jinja_environment.filters['js_string'] = jinja_filters.js_string

        return jinja_environment
Пример #6
0
    def get_jinja2env(self):
        """Initialise and return a jinja2 Environment instance."""
        global _jinja_env_cache

        if not _jinja_env_cache:
            env = jinja2.Environment(
                loader=jinja2.FileSystemLoader(gaetkconfig.TEMPLATE_DIRS),
                auto_reload=False,  # unneeded on App Engine production
                trim_blocks=True,  # first newline after a block is removed
                # lstrip_blocks=True,
                bytecode_cache=jinja2.MemcachedBytecodeCache(memcache,
                                                             timeout=3600),
                # This needs jinja2 > Version 2.8
                autoescape=jinja2.select_autoescape(['html', 'xml']),
            )

            env.exception_handler = self._jinja2_exception_handler

            jinja_filters.register_custom_filters(env)
            env.policies['json.dumps_function'] = hujson2.htmlsafe_json_dumps
            env = self._add_jinja2env_globals(env)
            _jinja_env_cache = env

        return _jinja_env_cache
Пример #7
0
def JINJA_CONFIG():
    import jinja2
    from django.conf import settings
    from django.core.cache import cache
    config = {
        'extensions': [
            'jinja2.ext.do', 'jinja2.ext.with_', 'jinja2.ext.loopcontrols',
            'jinja2.ext.i18n', 'waffle.jinja.WaffleExtension'
        ],
        'autoescape':
        True,
        'finalize':
        lambda x: x if x is not None else ''
    }
    if False and not settings.DEBUG:
        # We're passing the _cache object directly to jinja because
        # Django can't store binary directly; it enforces unicode on it.
        # Details: http://jinja.pocoo.org/2/documentation/api#bytecode-cache
        # and in the errors you get when you try it the other way.
        bc = jinja2.MemcachedBytecodeCache(cache._cache,
                                           "%sj2:" % settings.CACHE_PREFIX)
        config['cache_size'] = -1  # Never clear the cache
        config['bytecode_cache'] = bc
    return config
Пример #8
0
 def _get_bytecode_cache(self):
     return jinja2.MemcachedBytecodeCache(client=self.cache)
Пример #9
0
# along with 5050.  If not, see <http://www.gnu.org/licenses/>.
#

import os
import webapp2
import jinja2
from google.appengine.api import memcache
from google.appengine.api import app_identity
from handlers import IndexHandler, RedirectHandler, ViewsUpdateBot

jinja_env = jinja2.Environment(
    # Loading templates from the filesystem
    loader=jinja2.FileSystemLoader(os.path.join(os.path.dirname(__file__),
                                                "")),
    # I'm using memcached as a cache for compiled templates
    bytecode_cache=jinja2.MemcachedBytecodeCache(client=memcache.Client()),
)

app = webapp2.WSGIApplication(
    routes=[
        webapp2.Route(r'/', handler=IndexHandler),
        webapp2.Route(r'/<url_id:[a-zA-Z0-9]*>', handler=RedirectHandler),
        webapp2.Route(r'/update-views', handler=ViewsUpdateBot)
    ],
    # The appengine dev environ sets SERVER_SOFTWARE to Dev...
    debug=os.environ.get("SERVER_SOFTWARE").startswith("Dev"),
    config={
        "jinja_env": jinja_env,
        "hostname": app_identity.get_default_version_hostname(),
    })
Пример #10
0
from google.appengine.api import memcache
import jinja2

import settings
import routes
import users
import decorators
import utils
from jinja2htmlcompress import jinja2htmlcompress

# Initialize jinja
jinja_environment = jinja2.Environment(
    autoescape=True,
    loader=jinja2.FileSystemLoader(settings.path_templates),
    bytecode_cache=jinja2.MemcachedBytecodeCache(
        memcache,
        prefix='jinja2/bytecode/',
        timeout=settings.cache.jinja_bytecode_timeout))

# Add html compressor
if settings.compress_html:
    jinja_environment.add_extension(jinja2htmlcompress.HTMLCompress)


def cache_lifetime(routeconfig_name=None, *args):

    return settings.cache.template_lifetime if routes.configs.get(
        routeconfig_name).cachable else None


def template_cachekey(routeconfig_name=None, *args):
    """
Пример #11
0
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import logging
import webapp2
import jinja2
import settings

from google.appengine.api import memcache

JINJA_ENV = jinja2.Environment(
  loader=jinja2.FileSystemLoader(settings.TEMPLATE_PATH),
  autoescape=settings.TEMPLATE_ESCAPE,
  bytecode_cache=jinja2.MemcachedBytecodeCache(memcache, prefix='jinja2/bytecode/', timeout=settings.JINJA2_BYTECODE_TIMEOUT)
)

class BaseHandler(webapp2.RequestHandler):
  """
    Extension of the normal RequestHandler

    - self.write() provides a quick way to write out plain text
    - self.render() provides a quick way to render templates with
      template variables
    - self.render_json() provides a quick way to respond with JSON
  """
    def write(self, data):
        """ Provides a quick way to write out plain text """
        self.response.headers['Content-Type'] = 'text/plain; charset=utf-8'
        self.response.out.write(data)
Пример #12
0
# coding: utf-8

import os, sys
import logging
import webapp2
import jinja2
from google.appengine.api import memcache
from ucf.config.ucfconfig import UcfConfig
from ucf.utils import ucffunc, jinjacustomfilters
import sateraito_inc
import sateraito_func

bcc = jinja2.MemcachedBytecodeCache(client=memcache.Client(),
                                    prefix='jinja2/bytecode/',
                                    timeout=None)

##################################################
# ルート

# デフォルトデザイン
path_for_default = os.path.join(os.path.dirname(__file__),
                                UcfConfig.TEMPLATES_FOLDER_PATH,
                                UcfConfig.TEMPLATE_LANGUAGE_DEFAULT_FOLDER,
                                UcfConfig.TEMPLATE_DEFAULT_DESIGN_TYPE)

# PC用
path_for_pc = os.path.join(os.path.dirname(__file__),
                           UcfConfig.TEMPLATES_FOLDER_PATH,
                           UcfConfig.TEMPLATE_LANGUAGE_DEFAULT_FOLDER,
                           UcfConfig.VALUE_DESIGN_TYPE_PC)
jinja_environment_for_pc = jinja2.Environment(loader=jinja2.FileSystemLoader(