Python string templater

I use this REST web service which returns various pattern strings as URLs, for example:

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

In Ruby, I can use

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

To obtain

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

Is there a way to do this in Python? I know about the% () patterns, but obviously they don't work here.

+3
source share
3 answers

Do not use fast hack.

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

+2
source

python 2.6 ,

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

python, 2.6, / , .

+4

I can’t give you the perfect solution, but you can try to use string.Template. You either pre-process your incoming URL and then use string.Template directly, e.g.

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'

using the default syntax $ {...} for substitute identifiers. Or you are a subclass string.Templateto manage an identifier pattern like

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

but I did not understand this.

0
source

Source: https://habr.com/ru/post/1714150/


All Articles