Created
April 29, 2018 20:41
-
-
Save ale-rt/f1827ae78fea987fcfd46995304eb811 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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