我是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')
问题:
( )
或引号' '
,而不会在视图中出现错误。感谢。
答案 0 :(得分:1)
如果您只是希望能够写出文本的原始表示形式,以保护您免受可能的转义问题,只需使用三重引号,也许可以使用一些简单的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)
答案 1 :(得分:0)
...如果要逐步添加内容,可以将响应用作类文件对象:
response = HttpResponse()
response.write("<p>Here's the text of the Web page.</p>")
response.write("<p>Here's another paragraph.</p>")
因此,请写下您的回复:
response = HttpResponse(mimetype='text/plain')
response['Content-Disposition'] = 'attachment; filename=script.py'
response.write("def ping(): \n")
response.write(" run('ping server01')\n")