forked from sgammon/apptools
/
core.py
447 lines (330 loc) · 12.1 KB
/
core.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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
# -*- coding: utf-8 -*-
## Base Imports
import os
import ndb
import config
import pprint
import random
import hashlib
import logging
import webapp2
# Datastructure Imports (shamelessly borrowed from Providence/Clarity)
from util import DictProxy
from util import ObjectProxy
from util import CallbackProxy
# Webapp2 Imports
from webapp2 import Request
from webapp2 import Response
from webapp2 import RequestHandler
from webapp2_extras import jinja2
from webapp2_extras.appengine import sessions_ndb
from webapp2_extras.appengine import sessions_memcache
## Assets API Bridge
from api.assets import AssetsMixin
## Output Components
from api.output import ModuleLoader
from api.output import CoreOutputLoader
## Resolve JSON Adapter
try:
import json
except ImportError:
try:
import simplejson as json
except ImportError:
logging.critical('No compatible JSON adapter found.')
_api_cache = {}
def _loadAPIModule(entry):
''' Callback to lazy-load an API module in tuple(path, item) format. '''
global _api_cache
if entry not in _api_cache:
if isinstance(entry, tuple):
path, name = entry
mod = __import__(path, globals(), locals(), [name])
_api_cache[entry] = getattr(mod, name)
elif isinstance(entry, basestring):
mod = __import__(entry, globals(), locals(), ['*'])
_api_cache[entry] = mod
else:
logging.error('Lazyloader failed to resolve module for shortcut: "'+str(entry)+'".')
raise ImportError, "Could not resolve module for entry '"+str(entry)+"'."
return _api_cache[entry]
_apibridge = CallbackProxy(_loadAPIModule, {
''' Lazy-loaded bridge to AppEngine API services. '''
'db': ('google.appengine.ext', 'db'),
'xmpp': ('google.appengine.api', 'xmpp'),
'mail': ('google.appengine.api', 'mail'),
'oauth': ('google.appengine.api', 'oauth'),
'users': ('google.appengine.api', 'users'),
'images': ('google.appengine.api', 'images'),
'channel': ('google.appengine.api', 'channel'),
'backends': ('google.appengine.api', 'backends'),
'memcache': ('google.appengine.api', 'memcache'),
'urlfetch': ('google.appengine.api', 'urlfetch'),
'blobstore': ('google.appengine.ext', 'blobstore'),
'taskqueue': ('google.appengine.api', 'taskqueue'),
'capabilities': ('google.appengine.api', 'capabilities'),
'identity': ('google.appengine.api', 'app_identity'),
'multitenancy': ('google.appengine.api', 'namespace_manager'),
'matcher': ('google.appengine.api', 'prospective_search')
})
_extbridge = CallbackProxy(_loadAPIModule, {
''' Lazy-loaded bridge to useful AppEngine libs. '''
'ndb': 'ndb',
'pipelines': 'pipeline',
'mapreduce': 'mapreduce',
})
_utilbridge = CallbackProxy(_loadAPIModule, {
''' Lazy-loaded bridge to util libs that AppTools integrates with. '''
'wtforms': 'wtforms',
'timesince': ('util', 'timesince'),
'byteconvert': ('util', 'byteconvert'),
'httpagentparser': ('util', 'httpagentparser')
})
class BaseHandler(RequestHandler, AssetsMixin):
''' Top-level parent class for request handlers in AppTools. '''
## 1: Class variables
configPath = 'apptools.project'
minify = unicode
response = Response
context = {}
uagent = {}
## 2: Shortcuts
api = _apibridge
ext = _extbridge
util = _utilbridge
## 3: HTTP Headers included in every response
baseHeaders = {
''' HTTP headers added to every response (override via headers kwarg on `render`). '''
'Cache-Control': 'no-cache', # Stop caching of responses from Python, by default
'X-Platform': 'AppTools/ProvidenceClarity-Embedded', # Indicate the platform that is serving this request
'X-Powered-By': 'Google App Engine/1.5.5-prerelease', # Indicate the SDK version
'X-UA-Compatible': 'IE=edge,chrome=1' # Enable compatibility with Chrome Frame, and force IE to render with the latest engine
}
## 4: Base template context
@webapp2.cached_property
def baseContext(self):
''' Base template context - available to every template at runtime. '''
logging.info('REQUEST ENVIRON: '+str(self.request.environ))
return {
## Utility stuff
'util': {
## Request Information
'request': {
'env': self.request.environ,
'body': self.request.body,
'headers': self.request.headers,
'method': self.request.method,
'scheme': self.request.scheme,
'remote_user': self.request.remote_user,
'remote_addr': self.request.remote_addr,
'host': self.request.host,
'host_url': self.request.host_url,
'path': self.request.path,
'query_string': self.request.query_string,
'hash': os.environ.get('REQUEST_ID_HASH'),
'namespace': _apibridge.multitenancy.get_namespace()
},
## App Information
'appengine': {
'instance': os.environ.get('INSTANCE_ID'),
'current_version': os.environ.get('CURRENT_VERSION_ID'),
'datacenter': os.environ.get('DATACENTER'),
'software': os.environ.get('SERVER_SOFTWARE'),
'backend': _apibridge.backends.get_backend()
},
## Main Environ & Config
'env': os.environ,
'config': {
'get': config.config.get,
'debug': config.debug,
'project': self._projectConfig
},
## Converters
'converters': {
'json': json, ## SimpleJSON or Py2.7 JSON
'timesince': self.util.timesince, ## Util library for "15 minutes ago"-type text from datetimes
'byteconvert': self.util.byteconvert ## Util library for formatting data storage amounts
},
## Rand
'random': {
'random': random.random,
'randint': random.randint,
'randrange': random.randrange
},
## Other utils
'pprint': pprint.pprint,
},
## API Shortcuts
'api': {
'users': {
'is_current_user_admin': _apibridge.users.is_current_user_admin,
'current_user': _apibridge.users.get_current_user,
'create_login_url': _apibridge.users.create_login_url,
'create_logout_url': _apibridge.users.create_logout_url
},
'backends': _apibridge.backends,
'multitenancy': _apibridge.multitenancy
},
## flags for the page
'page': {
'ie': False, ## flag that we're serving to IE
'mobile': False, ## flag that we're serving to mobile
'appcache': { ## whether to enable HTML5 appcaching
'enabled': False,
'location': None,
}
},
}
## 5: Internal methods
def dispatch(self):
''' Sniff the Uagent header, then pass off to Webapp2. '''
# Parse useragent
if self.request.headers.get('User-Agent', None) is not None:
try:
self.uagent = httpagentparser.detect(self.request.headers.get('User-Agent'))
except Exception, e:
logging.warning('Exception encountered parsing uagent: '+str(e))
pass
return super(BaseHandler, self).dispatch()
@webapp2.cached_property
def config(self):
''' Cached shortcut to global config. '''
return config.config
@webapp2.cached_property
def _sysConfig(self):
''' Cached shortcut to handler config. '''
return self.config.get(self.configPath)
@webapp2.cached_property
def _outputConfig(self):
''' Cached shortcut to output config. '''
return self.config.get(self.configPath+'.output')
@webapp2.cached_property
def _projectConfig(self):
''' Cached shortcut to project config. '''
return self.config.get('apptools.project')
@webapp2.cached_property
def _jinjaConfig(self):
''' Cached shortcut to Jinja2 config. '''
return self.config.get('webapp2_extras.jinja2')
@webapp2.cached_property
def jinja2(self):
''' Cached access to Jinja2. '''
return jinja2.get_jinja2(app=self.app, factory=self.jinja2EnvironmentFactory)
def jinja2EnvironmentFactory(self, app):
''' Returns a prepared Jinja2 environment. '''
templates_compiled_target = self._jinjaConfig.get('compiled_path')
use_compiled = not config.debug or self._jinjaConfig.get( 'force_compiled')
if templates_compiled_target is not None and use_compiled:
# Use precompiled templates loaded from a module or zip.
loader = ModuleLoader(templates_compiled_target)
else:
# Parse templates for every new environment instances.
loader = CoreOutputLoader(self._jinjaConfig.get('template_path'))
j2cfg = self._jinjaConfig
j2cfg['environment_args']['loader'] = loader
## Inject python builtins as globals, so they are available to macros
j2cfg['globals'] = {
## Python builtins
'all': all, 'any': any,
'int': int, 'str': str,
'len': len, 'map': map,
'max': max, 'min': min,
'zip': zip, 'bool': bool,
'list': list, 'dict': dict,
'tuple': tuple, 'range': range,
'round': round, 'slice': slice,
'xrange': xrange, 'filter': filter,
'reduce': reduce, 'sorted': sorted,
'unicode': unicode, 'reversed': reversed,
'isinstance': isinstance, 'issubclass': issubclass,
## uri_for shortcut
'link': webapp2.uri_for,
## assets API
'asset': {
## Link to the Assets API
'url': self.get_asset,
'image': self.get_img_asset,
'style': self.get_style_asset,
'script': self.get_script_asset
},
## System stuff
'version': str(self._sysConfig['version']['major'])+'.'+str(self._sysConfig['version']['minor'])+' '+str(self._sysConfig['version']['release'])
}
## Make & return template environment
environment = jinja2.Jinja2(app, config=j2cfg)
return environment
def _bindRuntimeTemplateContext(self, basecontext):
''' Bind variables to the template context related to the current request context. '''
## Detect if we're handling a request from IE, and if we are, tell the template context
if self.uagent:
if self.uagent['browser']['name'] == 'MSIE':
basecontext['page']['ie'] = True
if self.uagent['browser']['mobile'] == True:
basecontext['page']['mobile'] = True
return basecontext
def _setcontext(self, *args, **kwargs):
''' Take a data structure (list of tuples, dict, or kwargs) and assign the appropriate k, v to the template context. '''
if len(kwargs) > 0:
for k, v in kwargs.items():
self.context[k] = v
if len(args) > 0:
for arg in args:
if isinstance(arg, list):
if isinstance(arg[0], tuple):
for k, v in arg:
self.context[k] = v
elif isinstance(arg, dict):
for k, v in arg.items():
self.context[k] = v
return
## 5: Public methods
def minify(self, rendered_template):
''' Minify rendered template output. Override for custom minification function or monkeypatch to 'unicode' to disable completely. '''
import slimmer
minify = unicode ## default to unicode
# Read minification config + setup minification handler
if self._outputConfig.get('minify', False) is True:
if content_type == 'text/html':
minify = slimmer.html_slimmer
elif content_type == 'text/javascript':
from slimmer.js_function_slimmer import slim as slimjs
minify = slimjs
elif content_type == 'text/css':
minify = slimmer.css_slimmer
return minify(rendered_template)
def render(self, path, context={}, elements={}, content_type='text/html', headers={}, **kwargs):
''' Return a response containing a rendered Jinja template. Creates a session if one doesn't exist. '''
if isinstance(self.context, dict) and len(self.context) > 0:
tmp_context = self.context
self.context = self.baseContext
map(self._setcontext, tmp_context)
else:
self.context = self.baseContext
# Build response HTTP headers
response_headers = {}
for key, value in self.baseHeaders.items():
response_headers[key] = value
if len(headers) > 0:
for key, value in headers.items():
response_headers[key] = value
# Consider kwargs
if len(kwargs) > 0:
for k, v in kwargs.items():
self.context[k] = v
# Bind runtime-level template context
try:
self.context = self._bindRuntimeTemplateContext(self.context)
except NotImplementedError, e:
if config.debug:
raise ## in production, the show must go on...
else:
pass
## Bind elements
map(self._setcontext, elements)
## Render template and write
self.response.write(self.minify(self.jinja2.render_template(path, **self.context)))
## Set response headers & content type
self.response.headers = [(key, value) for key, value in response_headers.items()]
self.response.content_type = content_type
## Finished!
return