python简单的wsgi文件上传脚本-有什么问题? [英] python simple wsgi file upload script - What is wrong?

查看:155
本文介绍了python简单的wsgi文件上传脚本-有什么问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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脚本,它接收文件并将其写入磁盘.但是,执行后(选择了文件):

Above is my python wsgi script that receives a file and writes it to the disk. However, upon executing (with a file selected):

内部服务器错误 处理此请求时发生错误. 请求处理程序失败

Internal Server Error An error occurred processing this request. Request handler failed

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模块上相当愚蠢,我现在不知道要进步什么.有任何线索吗?

Being pretty daft at wsgi and cgi module I have no idea to progress at this moment. any clues?

推荐答案

environ['wsgi.input']是类似于对象的流.您首先需要将其缓存到类似对象的文件中,例如:tempfile.TemporaryFileStringIO(在python3中为io.BytesIO):

environ['wsgi.input'] is a stream like object. You need to cache it firstly to file like object, eg: tempfile.TemporaryFile or StringIO (io.BytesIO in 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

出于安全原因,请考虑屏蔽传递给FieldStorage

For safety reason consider to mask environ value which you pass to FieldStorage

这篇关于python简单的wsgi文件上传脚本-有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆