views:

175

answers:

3

I'm using this REST web service, which returns various templated strings as urls, for example:

"http://api.app.com/{foo}"

In Ruby, I can then use

url = Addressable::Template.new("http://api.app.com/{foo}").expand('foo' => 'bar')

to get

"http://api.app.com/bar"

Is there any way to do this in Python? I know about %() templates, but obviously they're not working here.

+4  A: 

In python 2.6 you can do this if you need exactly that syntax

from string import Formatter
f = Formatter()
f.format("http://api.app.com/{foo}", foo="bar")

If you need to use an earlier python version then you can either copy the 2.6 formatter class or hand roll a parser/regex to do it.

Peter Ellis
A: 

I cannot give you a perfect solution but you could try using string.Template. You either pre-process your incoming URL and then use string.Template directly, like

In [6]: url="http://api.app.com/{foo}"
In [7]: up=string.Template(re.sub("{", "${", url))
In [8]: up.substitute({"foo":"bar"})
Out[8]: 'http://api.app.com/bar'

taking advantage of the default "${...}" syntax for replacement identifiers. Or you subclass string.Template to control the identifier pattern, like

class MyTemplate(string.Template):
    delimiter = ...
    pattern   = ...

but I haven't figured that out.

ThomasH
+2  A: 

Don't use a quick hack.

What is used there (and implemented by Addressable) are URI Templates. There seem to be several libs for this in python, for example: uri-templates. described_routes_py also has a parser for them.

Skade