Skip to content

Instantly share code, notes, and snippets.

@vangheem
Created June 26, 2014 13:26
Show Gist options
  • Save vangheem/2c625d89c33c1010662c to your computer and use it in GitHub Desktop.
Save vangheem/2c625d89c33c1010662c to your computer and use it in GitHub Desktop.
alternative renderTiles
def renderTiles(request, tree):
"""
copy from blocks minus ESI stuff
"""
site = getSite()
siteUrl = site.absolute_url()
try:
root = tree.getroot()
except AttributeError:
root = tree
headNode = root.find('head')
baseURL = request.getURL()
if request.getVirtualRoot():
# plone.subrequest deals with VHM requests
baseURL = ''
contexts = {}
original_data = request.form.get('data')
for tileNode in blocksutils.bodyTileXPath(tree):
tileHref = tileNode.attrib[blocksutils.tileAttrib]
tileTree = None
if not tileHref.startswith('/'):
tileHref = urljoin(baseURL, tileHref)
try:
# first try to resolve manually, this will be much faster than
# doing the subrequest
relHref = tileHref[len(siteUrl) + 1:]
contextPath, tilePart = relHref.split('@@', 1)
contextPath = contextPath.strip('/')
if contextPath not in contexts:
contexts[contextPath] = site.restrictedTraverse(contextPath)
context = contexts[contextPath]
if '?data=' in tilePart:
tileName, tileData = tilePart.split('?data=', 1)
else:
tileName = tilePart
tileData = '{}'
tileName = tileName.split('/')[0]
request.form['data'] = tileData
try:
tile = getMultiAdapter((context, request), name=tileName)
except ComponentLookupError:
continue
try:
res = tile()
except:
# error rendering, let's just cut out...
logger.error(
'nasty uncaught tile error, data: %s,\n%s' % (
'/'.join(context.getPhysicalPath()),
repr(tileData),
traceback.format_exc()))
res = """<html><body>
<p class="tileerror">
We apologize, there was an error rendering this snippet
</p></body></html>"""
try:
tileTree = html.fromstring(res).getroottree()
except:
continue
finally:
# just need to make sure this is cleared
if 'tile.data' in request.other:
del request.other['tile.data']
except:
# fallback to subrequest route, slower but safer?
try:
tileTree = blocksutils.resolve(tileHref)
except NotFound:
continue
except RuntimeError:
logger.info('error parsing tile url %s' % tileHref)
continue
except etree.XMLSyntaxError:
logger.info('error parsing tile url %s' % tileHref)
continue
if tileTree is not None:
tileRoot = tileTree.getroot()
tileHead = tileRoot.find('head')
if tileHead is not None:
for tileHeadChild in tileHead:
headNode.append(tileHeadChild)
blocksutils.replace_content(tileNode, tileRoot.find('body'))
if original_data:
# request data on the request form
request.form['data'] = original_data
elif 'data' in request.form:
# delete if there was no data on original request
del request.form['data']
return tree
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment