我正在编写一个自动脚本来填充服务器的一些配置文件,并且我遇到了 nginx 配置文件的问题。它包含两种可识别的 format() 关键字($
和{}
),我只想用花括号填充这些关键字。问题是我无法转义 $proxy_add_x_forwarded_for 之类的关键字(我应该可以使用,$$
但由于某种原因它不起作用)并且脚本返回 KeyErrors。有没有人知道我该如何摆脱这种情况?
nginx.conf(在这种情况下为实例名称)
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 的解决方案也是正确的,但这不是我想要的