蟒蛇简单的WSGI文件上传脚本 - 什么是错的?(python simple wsgi file u

2019-08-08 10:12发布

import os, cgi

#self_hosting script
tags = """<form enctype="multipart/form-data" action="save_file.py" method="post">
<p>File: <input type="file" name="file"></p>
<p><input type="submit" value="Upload"></p>
</form>"""

def Request(environ, start_response):
    # use cgi module to read data
    form = cgi.FieldStorage(fp=environ['wsgi.input'], environ=environ, keep_blank_values=True)

    try:
        fileitem = form['file']
    except KeyError:
        fileitem = None

    if fileitem and fileitem.file:
        fn = os.path.basename(fileitem.filename)
        with open(fn, 'wb') as f:
            data = fileitem.file.read(1024)
            while data:
                f.write(data)
                data = fileitem.file.read(1024)

            message = 'The file "' + fn + '" was uploaded successfully'

    else :
        message = 'please upload a file.'


    start_response('200 OK', [('Content-type','text/html')])

    return [message + "<br / >" + tags]

上面是我收到一个文件,并将其写入到磁盘的Python脚本WSGI。 然而,在(与选定的一个文件)执行:

内部服务器错误发生错误处理这个请求。 请求处理失败

Traceback (most recent call last):
  File "C:\Python26\Http\Isapi.py", line 110, in Request
    return Handler(Name)
  File "C:\Python26\Http\Isapi.py", line 93, in 
    "/apps/py/" : lambda P: RunWSGIWrapper(P),
  File "C:\Python26\Http\Isapi.py", line 86, in RunWSGIWrapper
    return RunWSGI(ScriptHandlers[Path])
  File "C:\Python26\Http\WSGI.py", line 155, in RunWSGI
    Result = Application(Environ, StartResponse)
  File "\\?\C:\Python26\html\save_file.py", line 13, in Request
    form = cgi.FieldStorage(fp=environ['wsgi.input'], environ=environ, keep_blank_values=True)
  File "C:\Python26\Lib\cgi.py", line 496, in __init__
    self.read_multi(environ, keep_blank_values, strict_parsing)
  File "C:\Python26\Lib\cgi.py", line 620, in read_multi
    environ, keep_blank_values, strict_parsing)
  File "C:\Python26\Lib\cgi.py", line 498, in __init__
    self.read_single()
  File "C:\Python26\Lib\cgi.py", line 635, in read_single
    self.read_lines()
  File "C:\Python26\Lib\cgi.py", line 657, in read_lines
    self.read_lines_to_outerboundary()
  File "C:\Python26\Lib\cgi.py", line 685, in read_lines_to_outerboundary
    line = self.fp.readline(1<<16)
AttributeError: 'module' object has no attribute 'readline'

处于WSGI和CGI模块非常愚蠢,我不知道在这一刻进步。 任何线索?

Answer 1:

environ['wsgi.input']是像对象的流。 你需要先缓存到文件状物品,如: tempfile.TemporaryFileStringIOio.BytesIO在python3):

from tempfile import TemporaryFile
import os, cgi

def read(environ):
    length = int(environ.get('CONTENT_LENGTH', 0))
    stream = environ['wsgi.input']
    body = TemporaryFile(mode='w+b')
    while length > 0:
        part = stream.read(min(length, 1024*200)) # 200KB buffer size
        if not part: break
        body.write(part)
        length -= len(part)
    body.seek(0)
    environ['wsgi.input'] = body
    return body

def Request(environ, start_response):
    # use cgi module to read data
    body = read(environ)
    form = cgi.FieldStorage(fp=body, environ=environ, keep_blank_values=True)
    # rest of your code

出于安全原因考虑,以掩盖environ其中传递价值FieldStorage



Answer 2:

自 - 答:对不起,我没有说,这是特定PyISAPIe-问题。 的类文件对象environ['wsgi.input']不具有readline()方法等其他environ在不同WSGI实现会做可变因素。

的(低效的解决方法)是节省一切从ENVIRON [“wsgi.input”]为tempfile ,并将它传递到FieldStorage

所以:

import tempfile, cgi
def some_wsgi_app(environ, start_response):
    temp_file = tempfile.TemporaryFile()
    temp_file.write(environ['wsgi.input'].read()) # or use buffered read()
    temp_file.seek(0)
    form = cgi.FieldStorage(fp=temp_file, environ=environ, keep_blank_values=True)
    # do_something #
    temp_file.close() #close and destroy temp file

    # ... start_response, return ... #

不过上面的例子将失败,如果从用户上载的数据太大而无法正常工作。



文章来源: python simple wsgi file upload script - What is wrong?