-
Notifications
You must be signed in to change notification settings - Fork 105
/
micolog_template.py
224 lines (175 loc) · 6.79 KB
/
micolog_template.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# 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.
#
"""A simple wrapper for Django templates.
The main purpose of this module is to hide all of the package import pain
you normally have to go through to get Django to work. We expose the Django
Template and Context classes from this module, handling the import nonsense
on behalf of clients.
Typical usage:
from google.appengine.ext.webapp import template
print template.render('templates/index.html', {'foo': 'bar'})
Django uses a global setting for the directory in which it looks for templates.
This is not natural in the context of the webapp module, so our load method
takes in a complete template path, and we set these settings on the fly
automatically. Because we have to set and use a global setting on every
method call, this module is not thread safe, though that is not an issue
for applications.
Django template documentation is available at:
http://www.djangoproject.com/documentation/templates/
"""
import hashlib
import os,logging
from google.appengine.dist import use_library
use_library('django', '1.2')
import django
import django.conf
try:
django.conf.settings.configure(
DEBUG=False,
TEMPLATE_DEBUG=False,
TEMPLATE_LOADERS=(
'django.template.loaders.filesystem.load_template_source',
),
)
except (EnvironmentError, RuntimeError):
pass
import django.template
import django.template.loader
from google.appengine.ext import webapp
def render(theme,template_file, template_dict, debug=False):
"""Renders the template at the given path with the given dict of values.
Example usage:
render("templates/index.html", {"name": "Bret", "values": [1, 2, 3]})
Args:
template_path: path to a Django template
template_dict: dictionary of values to apply to the template
"""
t = load(theme,template_file, debug)
return t.render(Context(template_dict))
template_cache = {}
def load(theme,template_file, debug=False):
"""Loads the Django template from the given path.
It is better to use this function than to construct a Template using the
class below because Django requires you to load the template with a method
if you want imports and extends to work in the template.
"""
#template_file=os.path.join("templates",template_file)
if theme.isZip:
theme_path=theme.server_dir
else:
theme_path=os.path.join( theme.server_dir,"templates")
abspath =os.path.join( theme_path,template_file)
logging.debug("theme_path:%s,abspath:%s"%(theme_path,abspath))
if not debug:
template = template_cache.get(abspath)
else:
template = None
if not template:
#file_name = os.path.split(abspath)
new_settings = {
'TEMPLATE_DIRS': (theme_path,),
'TEMPLATE_DEBUG': debug,
'DEBUG': debug,
}
old_settings = _swap_settings(new_settings)
try:
template = django.template.loader.get_template(template_file)
finally:
_swap_settings(old_settings)
if not debug:
template_cache[abspath] = template
def wrap_render(context, orig_render=template.render):
URLNode = django.template.defaulttags.URLNode
save_urlnode_render = URLNode.render
old_settings = _swap_settings(new_settings)
try:
URLNode.render = _urlnode_render_replacement
return orig_render(context)
finally:
_swap_settings(old_settings)
URLNode.render = save_urlnode_render
template.render = wrap_render
return template
def _swap_settings(new):
"""Swap in selected Django settings, returning old settings.
Example:
save = _swap_settings({'X': 1, 'Y': 2})
try:
...new settings for X and Y are in effect here...
finally:
_swap_settings(save)
Args:
new: A dict containing settings to change; the keys should
be setting names and the values settings values.
Returns:
Another dict structured the same was as the argument containing
the original settings. Original settings that were not set at all
are returned as None, and will be restored as None by the
'finally' clause in the example above. This shouldn't matter; we
can't delete settings that are given as None, since None is also a
legitimate value for some settings. Creating a separate flag value
for 'unset' settings seems overkill as there is no known use case.
"""
settings = django.conf.settings
old = {}
for key, value in new.iteritems():
old[key] = getattr(settings, key, None)
setattr(settings, key, value)
return old
def create_template_register():
"""Used to extend the Django template library with custom filters and tags.
To extend the template library with a custom filter module, create a Python
module, and create a module-level variable named "register", and register
all custom filters to it as described at
http://www.djangoproject.com/documentation/templates_python/
#extending-the-template-system:
templatefilters.py
==================
register = webapp.template.create_template_register()
def cut(value, arg):
return value.replace(arg, '')
register.filter(cut)
Then, register the custom template module with the register_template_library
function below in your application module:
myapp.py
========
webapp.template.register_template_library('templatefilters')
"""
return django.template.Library()
def register_template_library(package_name):
"""Registers a template extension module to make it usable in templates.
See the documentation for create_template_register for more information."""
if not django.template.libraries.get(package_name):
django.template.add_to_builtins(package_name)
Template = django.template.Template
Context = django.template.Context
def _urlnode_render_replacement(self, context):
"""Replacement for django's {% url %} block.
This version uses WSGIApplication's url mapping to create urls.
Examples:
<a href="{% url MyPageHandler "overview" %}">
{% url MyPageHandler implicit_args=False %}
{% url MyPageHandler "calendar" %}
{% url MyPageHandler "jsmith","calendar" %}
"""
args = [arg.resolve(context) for arg in self.args]
try:
app = webapp.WSGIApplication.active_instance
handler = app.get_registered_handler_by_name(self.view_name)
return handler.get_url(implicit_args=True, *args)
except webapp.NoUrlFoundError:
return ''