我是 Django 的新手,正在尝试将表单的结果输出到带有缩进的文本文件中。我已经阅读了文档,只能找到编写 CSV 输出的编写器。最终,我试图根据来自表单的输入生成可下载的 Python 脚本。由于 Python 需要准确的缩进,我无法正确输出。
这是我用来生成输出的部分观点:
if form.is_valid():
ServerName = form.cleaned_data.get('ServerName')
response = HttpResponse(mimetype='text/plain')
response['Content-Disposition'] = 'attachment; filename=script.py'
writer = csv.writer(response)
writer.writerow(['def ping ():'])
writer.writerow(['run ('ping ServerName')])
return response
我希望 script.py 的输出是这样的:
def ping():
run('ping server01')
问题:
- 我是否使用了正确的编写器来输出到文本文件?
- 如何在输出中添加缩进?
- 如何在输出中添加方括号,即:
( )或引号' '而不会在 View 中出现错误。
谢谢。
请您参考如下方法:
如果您只是希望能够写出文本的原始字面表示,同时也可以保护您免受可能的转义问题的影响,只需使用三重引号和一些简单的 dict 关键字格式即可:
ServerName = form.cleaned_data.get('ServerName')
py_script = """
def ping():
run('ping %(ServerName)s')
""" % locals()
response.write(py_script)
或者有更多的值:
ServerName = form.cleaned_data.get('ServerName')
foo = 'foo'
bar = 'bar'
py_script = """
def ping():
run('ping %(ServerName)s')
print "[%(foo)s]"
print '(%(bar)s)'
""" % locals()
response.write(py_script)
