Ticket #2467: dependencies.diff
| File dependencies.diff, 18.8 KB (added by lambacck, 2 years ago) |
|---|
-
tg/configuration.py
# HG changeset patch # User Chris Lambacher <chris@kateandchris.net> # Date 1266875077 18000 # Node ID 764e8ea349b56b2810e2b55dfd609bced50ff4d7 # Parent 749b487fb15fd46c3465ccfda42d60497cb25be8 # Parent 0af7aa9ed0df6ee5fea265948c8ce93801bf27b6 Make dependence on ToscaWidgets, Genshi and Mako follow configuration. diff -r 749b487fb15f -r 764e8ea349b5 tg/configuration.py
a b 7 7 from UserDict import DictMixin 8 8 9 9 from pylons.i18n import ugettext 10 from genshi.filters import Translator11 10 12 11 from pylons.configuration import config as pylons_config 13 12 from beaker.middleware import SessionMiddleware, CacheMiddleware … … 26 25 from routes.middleware import RoutesMiddleware 27 26 from webob import Request 28 27 29 from tw.api import make_middleware as tw_middleware30 31 28 log = logging.getLogger(__name__) 32 29 33 30 class TGConfigError(Exception):pass … … 354 351 if use_dotted_templatenames: 355 352 # Support dotted names by injecting a slightly different template 356 353 # lookup system that will return templates from dotted template notation. 357 from tg.dottednames upportimport DottedTemplateLookup354 from tg.dottednames.mako_lookup import DottedTemplateLookup 358 355 config['pylons.app_globals'].mako_lookup = DottedTemplateLookup( 359 356 input_encoding='utf-8', output_encoding='utf-8', 360 357 imports=['from webhelpers.html import escape'], … … 392 389 filter, template loader 393 390 394 391 """ 395 from tg.dottednames upportimport GenshiTemplateLoader392 from tg.dottednames.genshi_lookup import GenshiTemplateLoader 396 393 from tg.render import render_genshi 397 394 398 395 def template_loaded(template): … … 450 447 config['buffet.template_engines'].pop() 451 448 template_location = '%s.templates' % self.package.__name__ 452 449 template_location = '%s.templates' % self.package.__name__ 450 from genshi.filters import Translator 453 451 454 452 def template_loaded(template): 455 453 template.filters.insert(0, Translator(ugettext)) … … 681 679 682 680 683 681 """ 682 from tw.api import make_middleware as tw_middleware 683 684 684 685 685 twconfig = {'toscawidgets.framework.default_view': self.default_renderer, 686 686 'toscawidgets.framework.translator': ugettext, -
tg/controllers/decoratedcontroller.py
diff -r 749b487fb15f -r 764e8ea349b5 tg/controllers/decoratedcontroller.py
a b 15 15 from pylons.controllers.util import abort 16 16 17 17 from repoze.what.predicates import NotAuthorizedError as WhatNotAuthorizedError, not_anonymous 18 import tw 18 19 # demand load tw (ToscaWidets) if needed 20 tw = None 19 21 20 22 from tg.render import render as tg_render 21 23 from tg.decorators import expose … … 267 269 268 270 #set up the tw renderer 269 271 if engine_name in ('genshi','mako') and config['use_toscawidgets']: 272 global tw 273 if not tw: 274 import tw 275 270 276 tw.framework.default_view = engine_name 271 277 272 278 # Setup the template namespace, removing anything that the user -
new file tg/dottednames/genshi_lookup.py
diff -r 749b487fb15f -r 764e8ea349b5 tg/dottednames/genshi_lookup.py
- + 1 """Reimplementation of the Genshi template loader that supports dotted names.""" 2 3 import os 4 import stat 5 6 from genshi.template import TemplateLoader 7 8 import tg 9 10 11 class GenshiTemplateLoader(TemplateLoader): 12 """Genshi template loader that supports 13 zipped applications and dotted filenames as well as path names 14 """ 15 16 def load(self, filename, relative_to=None, cls=None, encoding=None): 17 """real loader function. copy paste from the mako template 18 loader. 19 """ 20 # TODO: get the template extension from the config!! 21 if not filename.endswith('.html'): 22 filename = tg.config['pylons.app_globals' 23 ].dotted_filename_finder.get_dotted_filename( 24 template_name=filename, 25 template_extension='.html') 26 27 return TemplateLoader.load(self, filename, 28 relative_to=relative_to, cls=cls, encoding=encoding) 29 -
new file tg/dottednames/mako_lookup.py
diff -r 749b487fb15f -r 764e8ea349b5 tg/dottednames/mako_lookup.py
- + 1 """Reimplementation of the Mako template loader that supports dotted names.""" 2 3 import os 4 import stat 5 6 try: 7 import threading 8 except ImportError: 9 import dummy_threading as threading 10 11 12 from mako.template import Template 13 from paste.deploy.converters import asbool 14 15 import tg 16 17 18 class DottedTemplateLookup(object): 19 """Mako template lookup emulation that supports 20 zipped applications and dotted filenames. 21 22 This is an emulation of the Mako template lookup that will handle 23 get_template and support dotted names in Python path notation 24 to support zipped eggs. 25 26 This is necessary because Mako asserts that your project will always 27 be installed in a zip-unsafe manner with all files somewhere on the 28 hard drive. 29 30 This is not the case when you want your application to be deployed 31 in a single zip file (zip-safe). If you want to deploy in a zip 32 file _and_ use the dotted template name notation then this class 33 is necessary because it emulates files on the filesystem for the 34 underlying Mako engine while they are in fact in your zip file. 35 36 """ 37 38 def __init__(self, input_encoding, output_encoding, 39 imports, default_filters, module_directory=None): 40 41 self.input_encoding = input_encoding 42 self.output_encoding = output_encoding 43 self.imports = imports 44 self.default_filters = default_filters 45 # implement a cache for the loaded templates 46 self.template_cache = dict() 47 # implement a cache for the filename lookups 48 self.template_filenames_cache = dict() 49 self.module_directory = module_directory 50 51 # a mutex to ensure thread safeness during template loading 52 self._mutex = threading.Lock() 53 54 def adjust_uri(self, uri, relativeto): 55 """Adjust the given uri relative to a filename. 56 57 This method is used by mako for filesystem based reasons. 58 In dotted lookup land we don't adjust uri so we just return 59 the value we are given without any change. 60 61 """ 62 if uri.startswith('local:'): 63 uri = tg.config['pylons.package'] + '.' + uri[6:] 64 65 if '.' in uri: 66 # We are in the DottedTemplateLookup system so dots in 67 # names should be treated as a Python path. Since this 68 # method is called by template inheritance we must 69 # support dotted names also in the inheritance. 70 result = tg.config['pylons.app_globals'].\ 71 dotted_filename_finder.get_dotted_filename(template_name=uri, template_extension='.mak') 72 73 if not uri in self.template_filenames_cache: 74 # feed our filename cache if needed. 75 self.template_filenames_cache[uri] = result 76 77 else: 78 # no dot detected, just return plain name 79 result = uri 80 81 return result 82 83 def __check(self, template): 84 """private method used to verify if a template has changed 85 since the last time it has been put in cache... 86 87 This method being based on the mtime of a real file this should 88 never be called on a zipped deployed application. 89 90 This method is a ~copy/paste of the original caching system from 91 the Mako lookup loader. 92 93 """ 94 if template.filename is None: 95 return template 96 97 98 if not os.path.exists(template.filename): 99 # remove from cache. 100 self.template_cache.pop(template.filename, None) 101 raise exceptions.TemplateLookupException( 102 "Cant locate template '%s'" % template.filename) 103 104 elif template.module._modified_time < os.stat( 105 template.filename)[stat.ST_MTIME]: 106 107 # cache is too old, remove old template 108 # from cache and reload. 109 self.template_cache.pop(template.filename, None) 110 return self.__load(template.filename) 111 112 else: 113 # cache is correct, use it. 114 return template 115 116 def __load(self, filename): 117 """real loader function. copy paste from the mako template 118 loader. 119 120 """ 121 # make sure the template loading from filesystem is only done 122 # one thread at a time to avoid bad clashes... 123 self._mutex.acquire() 124 try: 125 try: 126 # try returning from cache one more time in case 127 # concurrent thread already loaded 128 return self.template_cache[filename] 129 130 except KeyError: 131 # not in cache yet... we can continue normally 132 pass 133 134 try: 135 self.template_cache[filename] = Template( 136 filename=filename, 137 module_directory=self.module_directory, 138 input_encoding=self.input_encoding, 139 output_encoding=self.output_encoding, 140 default_filters=self.default_filters, 141 imports=self.imports, 142 lookup=self) 143 144 return self.template_cache[filename] 145 146 except: 147 self.template_cache.pop(filename, None) 148 raise 149 150 finally: 151 # _always_ release the lock once done to avoid 152 # "thread lock" effect 153 self._mutex.release() 154 155 def get_template(self, template_name): 156 """this is the emulated method that must return a template 157 instance based on a given template name 158 """ 159 160 if not self.template_cache.has_key(template_name): 161 # the template string is not yet loaded into the cache. 162 # Do so now 163 self.__load(template_name) 164 165 if asbool(tg.config.get('templating.mako.reloadfromdisk', 'false')): 166 # AUTO RELOADING will be activated only if user has 167 # explicitly asked for it in the configuration 168 # return the template, but first make sure it's not outdated 169 # and if outdated, refresh the cache. 170 return self.__check(self.template_cache[template_name]) 171 172 else: 173 return self.template_cache[template_name] 174 -
deleted file tg/dottednamesupport.py
diff -r 749b487fb15f -r 764e8ea349b5 tg/dottednamesupport.py
+ - 1 """Reimplementation of the Mako template loader that supports dotted names."""2 3 import os4 import stat5 6 try:7 import threading8 except ImportError:9 import dummy_threading as threading10 11 12 from pkg_resources import resource_filename13 from mako.template import Template14 from genshi.template import TemplateLoader15 from paste.deploy.converters import asbool16 17 import tg18 19 20 class DottedTemplateLookup(object):21 """Mako template lookup emulation that supports22 zipped applications and dotted filenames.23 24 This is an emulation of the Mako template lookup that will handle25 get_template and support dotted names in Python path notation26 to support zipped eggs.27 28 This is necessary because Mako asserts that your project will always29 be installed in a zip-unsafe manner with all files somewhere on the30 hard drive.31 32 This is not the case when you want your application to be deployed33 in a single zip file (zip-safe). If you want to deploy in a zip34 file _and_ use the dotted template name notation then this class35 is necessary because it emulates files on the filesystem for the36 underlying Mako engine while they are in fact in your zip file.37 38 """39 40 def __init__(self, input_encoding, output_encoding,41 imports, default_filters, module_directory=None):42 43 self.input_encoding = input_encoding44 self.output_encoding = output_encoding45 self.imports = imports46 self.default_filters = default_filters47 # implement a cache for the loaded templates48 self.template_cache = dict()49 # implement a cache for the filename lookups50 self.template_filenames_cache = dict()51 self.module_directory = module_directory52 53 # a mutex to ensure thread safeness during template loading54 self._mutex = threading.Lock()55 56 def adjust_uri(self, uri, relativeto):57 """Adjust the given uri relative to a filename.58 59 This method is used by mako for filesystem based reasons.60 In dotted lookup land we don't adjust uri so we just return61 the value we are given without any change.62 63 """64 if uri.startswith('local:'):65 uri = tg.config['pylons.package'] + '.' + uri[6:]66 67 if '.' in uri:68 # We are in the DottedTemplateLookup system so dots in69 # names should be treated as a Python path. Since this70 # method is called by template inheritance we must71 # support dotted names also in the inheritance.72 result = tg.config['pylons.app_globals'].\73 dotted_filename_finder.get_dotted_filename(template_name=uri, template_extension='.mak')74 75 if not uri in self.template_filenames_cache:76 # feed our filename cache if needed.77 self.template_filenames_cache[uri] = result78 79 else:80 # no dot detected, just return plain name81 result = uri82 83 return result84 85 def __check(self, template):86 """private method used to verify if a template has changed87 since the last time it has been put in cache...88 89 This method being based on the mtime of a real file this should90 never be called on a zipped deployed application.91 92 This method is a ~copy/paste of the original caching system from93 the Mako lookup loader.94 95 """96 if template.filename is None:97 return template98 99 100 if not os.path.exists(template.filename):101 # remove from cache.102 self.template_cache.pop(template.filename, None)103 raise exceptions.TemplateLookupException(104 "Cant locate template '%s'" % template.filename)105 106 elif template.module._modified_time < os.stat(107 template.filename)[stat.ST_MTIME]:108 109 # cache is too old, remove old template110 # from cache and reload.111 self.template_cache.pop(template.filename, None)112 return self.__load(template.filename)113 114 else:115 # cache is correct, use it.116 return template117 118 def __load(self, filename):119 """real loader function. copy paste from the mako template120 loader.121 122 """123 # make sure the template loading from filesystem is only done124 # one thread at a time to avoid bad clashes...125 self._mutex.acquire()126 try:127 try:128 # try returning from cache one more time in case129 # concurrent thread already loaded130 return self.template_cache[filename]131 132 except KeyError:133 # not in cache yet... we can continue normally134 pass135 136 try:137 self.template_cache[filename] = Template(138 filename=filename,139 module_directory=self.module_directory,140 input_encoding=self.input_encoding,141 output_encoding=self.output_encoding,142 default_filters=self.default_filters,143 imports=self.imports,144 lookup=self)145 146 return self.template_cache[filename]147 148 except:149 self.template_cache.pop(filename, None)150 raise151 152 finally:153 # _always_ release the lock once done to avoid154 # "thread lock" effect155 self._mutex.release()156 157 def get_template(self, template_name):158 """this is the emulated method that must return a template159 instance based on a given template name160 """161 162 if not self.template_cache.has_key(template_name):163 # the template string is not yet loaded into the cache.164 # Do so now165 self.__load(template_name)166 167 if asbool(tg.config.get('templating.mako.reloadfromdisk', 'false')):168 # AUTO RELOADING will be activated only if user has169 # explicitly asked for it in the configuration170 # return the template, but first make sure it's not outdated171 # and if outdated, refresh the cache.172 return self.__check(self.template_cache[template_name])173 174 else:175 return self.template_cache[template_name]176 177 178 class GenshiTemplateLoader(TemplateLoader):179 """Genshi template loader that supports180 zipped applications and dotted filenames as well as path names181 """182 183 def load(self, filename, relative_to=None, cls=None, encoding=None):184 """real loader function. copy paste from the mako template185 loader.186 """187 # TODO: get the template extension from the config!!188 if not filename.endswith('.html'):189 filename = tg.config['pylons.app_globals'190 ].dotted_filename_finder.get_dotted_filename(191 template_name=filename,192 template_extension='.html')193 194 return TemplateLoader.load(self, filename,195 relative_to=relative_to, cls=cls, encoding=encoding)196 -
tg/render.py
diff -r 749b487fb15f -r 764e8ea349b5 tg/render.py
a b 1 1 from urllib import quote_plus 2 2 3 from genshi import HTML, XML4 3 from pylons.configuration import config 5 4 from paste.deploy.converters import asbool 6 5 from pylons import (app_globals, session, tmpl_context, request, … … 153 152 return render_genshi(template_name, template_vars, **kwargs) 154 153 155 154 155 # demand load these items from Genshi if needed 156 HTML = XML = None 156 157 def render_genshi(template_name, template_vars, **kwargs): 157 158 """Render the template_vars with the Genshi template""" 159 global HTML,XML 160 if not HTML or not XML: 161 from genshi import HTML,XML 162 158 163 template_vars.update(HTML=HTML, XML=XML) 159 164 160 165 if config.get('use_dotted_templatenames', False):