request: add a static_resource method to Request instances

master
Dustin C. Hatch 2012-11-19 21:35:31 -06:00
parent 5529b66a57
commit eb347e7fb5
1 changed files with 39 additions and 0 deletions

View File

@ -70,3 +70,42 @@ class Request(Request):
if vars:
url += '?' + urllib.urlencode(vars)
return url
def static_resource(self, path):
'''Return a URL to the given static resource
This method combines the defined static resource root URL with the
given path to construct a complete URL to the given resource. The
resource root should be defined in the application configuration
dictionary, under the name ``milla.static_root``, for example::
app = milla.Application(dispatcher)
app.config.update({
'milla.static_root': '/static/'
})
Then, calling ``static_resource`` on a :py:class:`Request` object
(i.e. inside a controller callable) would combine the given path
with ``/static/``, like this::
request.static_resource('/images/foo.png')
would return ``/static/images/foo.png``.
If no ``milla.static_root`` key is found in the configuration
dictionary, the path will be returned unaltered.
:param path: Path to the resource, relative to the defined root
'''
try:
root = self.config['milla.static_root']
except KeyError:
return path
if path.startswith('/'):
path = path[1:]
if not root.endswith('/'):
root += '/'
return urlparse.urljoin(root, path)