Skip to content

Instantly share code, notes, and snippets.

@ale-rt
Created April 29, 2018 20:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ale-rt/f1827ae78fea987fcfd46995304eb811 to your computer and use it in GitHub Desktop.
Save ale-rt/f1827ae78fea987fcfd46995304eb811 to your computer and use it in GitHub Desktop.
# coding=utf-8
from plone.app.blocks import utils
from plone.subrequest import subrequest
from zExceptions import NotFound
from zope.site.hooks import getSite
def resolveResource(url):
"""Resolve the given URL to a unicode string. If the URL is an absolute
path, it will be made relative to the Plone site root.
"""
site = getSite()
site_url = site.absolute_url()
if url.startswith(site_url):
url = url[len(site_url):]
if url.startswith('/'):
url = '/'.join(site.getPhysicalPath()) + url
response = subrequest(url)
if response.status == 404:
raise NotFound(url)
resolved = response.getBody()
if isinstance(resolved, str):
charset = utils.extractCharset(response)
resolved = resolved.decode(charset)
if response.status in (301, 302):
site = getSite()
location = response.headers.get('location') or ''
if location.startswith(site.absolute_url()):
return resolveResource(location[len(site.absolute_url()):])
elif response.status != 200:
raise RuntimeError(resolved)
return resolved
utils.resolveResource = resolveResource
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment