从HTML执行Python脚本
浏览器显示的是代码,而不是运行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,)
我尝试了论坛上发布的各种解决方案,但在我的情况下都没有效果。请告诉我需要改正什么。谢谢大家的快速帮助。
1 个回答
0
我刚好看到这个问题,我也遇到了同样的情况。你现在有答案了吗?
至于为什么你的代码不工作,是因为HTML没有把它当作Python文件来理解。这是我目前所理解的,因为我还没有解决我的问题。你需要某种解释器,让HTML能够理解Python文件。