2014-04-21 53 views
1

瀏覽器顯示代碼而不是運行python腳本。從html執行python腳本

的HTML代碼如下:

<html><body> 
<form enctype="multipart/form-data" action="/static/savefiles.py" method="post"> 
<p>File: <input type="file" name="file"></p> 
<p><input type="submit" value="Upload"></p> 
</form> 
</body></html> 

Python的代碼如下:

#!c:\Python27\python.exe 
#!/usr/bin/python 


from google.appengine.ext import webapp 
from google.appengine.ext.webapp.util import run_wsgi_app 
import cgi, os 
import cgitb; cgitb.enable() 



     try: # Windows needs stdio set for binary mode. 
      import msvcrt 
      msvcrt.setmode (0, os.O_BINARY) # stdin = 0 
      msvcrt.setmode (1, os.O_BINARY) # stdout = 1 
     except ImportError: 
      pass 

     form = cgi.FieldStorage() 

     # A nested FieldStorage instance holds the file 
     fileitem = form['file'] 

     # Test if the file was uploaded 
     if fileitem.filename: 

      # strip leading path from file name to avoid directory traversal attacks 
      fn = os.path.basename(fileitem.filename) 
      open(os.path.join('static/files/' + fn, 'wb')).write(fileitem.file.read()) 
      message = 'The file "' + fn + '" was uploaded successfully' 

     else: 
      message = 'No file was uploaded' 

     print """\ 
     Content-Type: text/html\n 
     <html><body> 
     <p>%s</p> 
     </body></html> 
     """ % (message,) 

我已經嘗試了多種在論壇上張貼的解決方案,但沒有人在工作我的情況。請指導我需要糾正什麼。非常感謝您的快速幫助。

+0

你使用什麼樣的網絡服務器?我想你必須將其配置爲用Python腳本標記文件夾爲cgi-bin – wubwubb

+0

我正在谷歌應用程序引擎上部署此代碼。我對Python非常陌生,幫助一位正在緊急休假的同事。你能解釋一下我應該怎麼做。 – user3556659

回答

0

我只是偶然發現了這個問題,我也遇到了同樣的問題。你現在有這個答案嗎?

至於爲什麼你的代碼不工作是因爲HTML不解釋它爲python文件。這是迄今爲止我瞭解的,因爲我還沒有解決我的問題。你需要某種解釋器來理解一個python文件。