I have an SQL template where I need to substitute random UUIDs.
from string import Template
import uuid
def gen_uuid():
return str(uuid.uuid4())
s = """
insert ... values('foo', ${uuid});
insert ... values('bar', ${uuid});
insert ... values('baz', ${uuid});
"""
mappings = {
"uuid": gen_uuid # how??
}
template = Template(s)
print template.safe_substitute(mappings)
How can I bind different UUIDs values to the same template key?
Update
Ok.. I ended up overriding getitem. Not ideal but works..
class UUIDDict(dict):
def __init__(self, *args, **kwargs):
self.update(*args, **kwargs)
def __getitem__(self, key):
if key == 'uuid':
return str(uuid.uuid4())
return super(UUIDDict, self).__getitem__(key)
string.Template() isn’t designed to substitute multiple values for a single key. Other templating systems may support this, but string.Template is meant to be dirt simple.
That being said, it isn’t hard to do what you want in a loop and then combine the results using str.join:
As suggested by the OP, a custom dictionary can be created that will build a new uuid() on each lookup: