我正在编写一个自动脚本来填充服务器的一些配置文件,我遇到了nginx配置文件的问题。它包含两种类型的已识别格式()关键字($
和{}
),我只想用花括号填充它们。问题是我无法逃避像$ proxy_add_x_forwarded_for这样的关键字(我应该可以使用$$
,但由于某种原因它不起作用)并且脚本返回KeyErrors。有没有人知道如何逃避这个?
nginx.conf(本例中为instance_name)
location /{instance_name} {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_set_header SCRIPT_NAME /{instance_name};
proxy_redirect off;
proxy_pass unix:/var/run/openmooc/askbot/{instance_name}.sock;
}
替换代码:
def _populate_file(self, original_file, values):
"""
Basic abstraction layer for populating files on demand
original_file has to be a path to the file in string format
values is a dictionary containing the necessary key:value pairs.
"""
f = open(original_file, 'r')
file_content = f.read()
f.close()
# Create a new populated file. We use ** so we can use keyword replacement
populated_settings = file_content.format(**values)
# Open the file in write mode so we can rewrite it
f = open(original_file, 'w')
f.write(populated_settings)
f.close()
# Call to action
template = os.path.join(INSTANCE_DIR, 'nginx.conf')
values = {'instance_name': instance_name}
self._populate_file(template, values)
已解决:正如@Blender所说,format()将整个位置块作为要替换的关键字。最简单的解决方案是使用双花括号来逃避它们。来自@FoxMaSk的解决方案也是正确的,但它不是我想要的
答案 0 :(得分:2)
你得到一个KeyError
,因为Python正在尝试格式化大括号内的整个块({\n proxy_set_header ... }
)。
您可能会发现使用旧的字符串格式化语法更容易:
"""location /%(instance_name)s {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_set_header SCRIPT_NAME /%(instance_name)s;
proxy_redirect off;
proxy_pass unix:/var/run/openmooc/askbot/%(instance_name)s.sock;
}""" % {'instance_name': 'foo_bar'}
或者只需手动搜索替换,@FoxMaSk suggested。
答案 1 :(得分:0)
而不是
populated_settings = file_content.format(**values)
str.replace应该做的伎俩
populated_settings = file_content.replace('{instance_name}',values['instance_name'])