2012-08-16 21 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")