python - Cherrypy:如何从上传的文件中获取原始数据?

标签 python cherrypy

我在使用 cherrypy 3.2.4 上传文件时遇到问题。 ( python 2.7) 我无法获取上传文件的原始数据。我试图调试以找到如何从响应中获取数据值但没有成功。有人知道如何解决这个问题吗?

彼得

这是我使用的代码:

    def index(self):
    return """
    <html><body>
        <h2>Upload a file</h2>
        <form action="upload" method="post" enctype="multipart/form-data">
        filename: <input type="file" name="myFile" /><br />
        <input type="submit" />
        </form>
        <h2>Download a file</h2>
        <a href='download'>This one</a>
    </body></html>
    """
index.exposed = True

def upload(self, myFile):
    out = """<html>
    <body>
        myFile length: %s<br />
        myFile filename: %s<br />
        myFile mime-type: %s
    </body>
    </html>"""


    cherrypy.log('-'*60)
    cherrypy.log('0: ' + str(dir(myFile)))
    cherrypy.log('-'*60)
    cherrypy.log('2: ' + str(dir(cherrypy.request.headers)))
    cherrypy.log('-'*60)
    cherrypy.log('4: ' + str(dir(cherrypy.request.rfile)))
    cherrypy.log('-'*60)
    cherrypy.log('6: ' + str(cherrypy.request.rfile.readline))
    cherrypy.log('-'*60)
    cherrypy.log('8: ' + str(cherrypy.request.rfile.read()))
    cherrypy.log('-'*60)
    cherrypy.log('-'*60)
    cherrypy.log('-'*60)
    # Although this just counts the file length, it demonstrates
    # how to read large files in chunks instead of all at once.
    # CherryPy reads the uploaded file into a temporary file;
    # myFile.file.read reads from that.
    size = 0
    while True:
        data = myFile.file.read(8192)
        if not data:
            break
        size += len(data)
    #cherrypy.log('myFile: %s' % str(dir(myFile)))
    #cherrypy.log('File: %s' % str(myFile.read_into_file))
    #myFile.read_into_file('a.txt')
    return out % (size, myFile.filename, myFile.content_type)
upload.exposed = True

这是输出:

[27/Jul/2014:13:38:32]  0: ['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__iter__', '__module__', '__new__', '__next__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'attempt_charsets', 'boundary', 'charset', 'content_type', 'default_content_type', 'default_proc', 'file', 'filename', 'fp', 'from_fp', 'fullvalue', 'headers', 'length', 'make_file', 'maxrambytes', 'name', 'next', 'params', 'part_class', 'parts', 'process', 'processors', 'read', 'read_headers', 'read_into_file', 'read_lines_to_boundary', 'readline', 'readlines', 'type', 'value']
[27/Jul/2014:13:38:32]  2: ['__class__', '__cmp__', '__contains__', '__delattr__', '__delitem__', '__dict__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__','__weakref__', 'clear', 'copy', 'elements', 'encode', 'encode_header_items', 'encodings', 'fromkeys', 'get', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'output', 'pop', 'popitem', 'protocol', 'setdefault', 'update', 'use_rfc_2047', 'values', 'viewitems', 'viewkeys', 'viewvalues']
[27/Jul/2014:13:38:32]  4: ['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__iter__', '__module__', '__new__', '__next__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'close', 'read', 'readline', 'readlines', 'remaining', 'rfile']
[27/Jul/2014:13:38:32]  6: <bound method KnownLengthRFile.readline of <cherrypy.wsgiserver.wsgiserver2.KnownLengthRFile object at 0x0000000002FF8D30>>
[27/Jul/2014:13:38:32]  8:
[27/Jul/2014:13:38:32] "POST /upload HTTP/1.1" 200 172 "http://localhost:8080/" "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:30.0) Gecko/20100101 Firefox/30.0"

已编辑:

我尝试并找到了简单的解决方案:

def upload(self, myFile):
    lcHDRS = {}
    for key, val in cherrypy.request.headers.iteritems():
        lcHDRS[key.lower()] = val

    incomingBytes = int(lcHDRS['content-length'])
    content = myFile.file.read(incomingBytes)
    file = open ('./upload/' + file.filename,"wb")
    file.write(content)
    file.close()                

    return 'File was uploaded...'

最佳答案

首先删除您的 cherrypy 日志语句。其中第 6 行是错误的。还将这些行添加到您的 while 循环中...

size = 0

# NEW LINE
all_data = bytearray()

while True:
    data = myFile.file.read(8192)

    # NEW LINE
    all_data += data

    if not data:
        break
    size += len(data)

    # to save the file use this

    saved_file=open(myFile.filename, 'wb') 
    saved_file.write(all_data) 
    saved_file.close()

return out % (size, myFile.filename, myFile.content_type)

现在您只能获得前 8192 个字节。

希望这对您有所帮助!

关于python - Cherrypy:如何从上传的文件中获取原始数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24980689/

相关文章:

python - wxPython线程阻塞

python - 在此程序中使用 try 和 except 在此 python 中

python - virtualenv --system-site-packages 不使用系统站点包

python - ASP.NET 成员(member)资格的开源替代方案

mysql - 如何在 CherryPy 3.2.2 的 MySQL 中存储 Web session ?

python - 如何一次拿走 N 件 M 件东西

python - 是否可以使用 pysftp 模块删除包含某些内容的目录?

python - 如何在本地部署 CherryPy 应用程序

python - 在 cherrypy 中启动 celery 任务

python - CherryPy 身份验证超时