2012-08-16 53 views
2

我是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') 

问题:

  1. 我使用正确的作家输出到文本文件?
  2. 如何将缩进添加到我的输出中?
  3. 如何添加括号(即:()或引号' ')到输出中,而不会在视图中出现错误。

谢谢。

+0

您是否已经生成完整的python脚本结构,并且只是想将其写入响应中?或者这是一个更复杂的问题,包括如何正确地将python的sytax组合成有效的结构? – jdi 2012-08-16 01:55:40

回答

1

如果你只是想能够写出一个李你的文字或双侧生表示,在某种程度上,也将保护您免受可能的逃避问题,只要用三报价,也许一些简单的字典关键字格式:

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) 
+0

此方法似乎将所有内容写在同一行上而没有任何缩进 – CraigH 2012-08-16 03:45:44

+0

它应该保留原始格式。你用纯文本MIME类型来看它吗?如果您打印该字符串,则会在其中看到换行符 – jdi 2012-08-16 03:59:57

0

documentation

...如果你想逐步添加的内容,你可以使用响应作为一个类文件对象:

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")