Generate config file from template using Python search and replace.

Peter Otten __peter__ at web.de
Tue Dec 1 09:41:04 EST 2015


Mr Zaug wrote:

> Actually, I don't understand what you mean by "all other braces." What
> braces are you talking about? The placeholders in the template file (the
> file being read in) have braces around them but they are not escaped.

The example you provide was

      $include "_dispatcher_publish_filters.any"
      /1000 { /type "allow"  /glob "* /CONTENT_PATH/*.html*" }
      /1001 { /type "allow"  /glob "POST /DAMPATH/www/*.html *" }

If you want to use string formatting to replace CONTENT_PATH and DAMPATH in 
the above excerpt you have to change the template to

      $include "_dispatcher_publish_filters.any"
      /1000 {{ /type "allow"  /glob "* /{CONTENT_PATH}/*.html*" }}
      /1001 {{ /type "allow"  /glob "POST /{DAMPATH}/www/*.html *" }}


> Also, do I really need curly braces to tell Python what my placeholders
> are?

Let's take a slightly modified example to answer that one:

      $include "_dispatcher_publish_filters.any"
      /1000 { /type "allow"  /glob "* /CONTENT_PATH/*.html*" }
      /1001 { /type "allow"  /glob "POST /DAMPATH/www/*.html *" }
      /1002 { /type "allow"  /glob "* /ALTERNATIVE_CONTENT_PATH/*.html*" }


If you try to fill in the CONTENT_PATH with 

    data = data.replace("CONTENT_PATH", "foo")

the result will be

      $include "_dispatcher_publish_filters.any"
      /1000 { /type "allow"  /glob "* /foo/*.html*" }
      /1001 { /type "allow"  /glob "POST /DAMPATH/www/*.html *" }
      /1002 { /type "allow"  /glob "* /ALTERNATIVE_foo/*.html*" }

Look at the butchered line starting with /1002, a problem that MRAB already 
pointed out before. The braces are not necessary if the string you are 
replacing doesn't occur elsewhere in the template, but they make the 
replacement process both flexible and unambiguous.




More information about the Python-list mailing list