【问题标题】:CherryPy upload fileCherryPy 上传文件
【发布时间】:2016-12-23 19:06:06
【问题描述】:

我想将一个文件从 python3 客户端发布到cherrypy。我正在使用请求库。 我的客户代码:

import requests

url = 'http://127.0.0.1:8080/upload'
files = {'file.zip': open('file.zip', 'rb')}

r = requests.post(url, files=files)

我的服务器代码:

import os
import tempfile
import shutil

import cherrypy


config = {
    'global' : {
        'server.socket_host' : '127.0.0.1',
        'server.socket_port' : 8080,
        'server.thread_pool' : 8,
        'server.max_request_body_size' : 0,
        'server.socket_timeout' : 60
  }
}


class App:
    @cherrypy.config(**{'response.timeout': 3600})
    @cherrypy.expose()
    def upload(self):
        '''Handle non-multipart upload'''

        destination = os.path.join('/home/uvv/upload')
        with open(destination, 'wb') as f:
            shutil.copyfileobj(cherrypy.request.body, f)

        return 'Okay'


if __name__ == '__main__':
        cherrypy.quickstart(App(), '/', config)

服务器返回错误:

127.0.0.1 - - [17/Aug/2016:11:38:49] "POST /upload HTTP/1.1" 400 2083 "" "python-requests/2.10.0"

【问题讨论】:

  • 这不是您发布的错误,而是日志条目。什么是 HTTP 响应正文?附言尝试在上传处理程序的开头添加日志以查看它是否被调用。
  • P.P.S.尝试先上传小文件
  • 并检查您是否有适当的权限从cherrypy应用程序写入/home/uvv/upload文件
  • 权限:a+rwx。文件没有上传
  • 那么响应正文是什么?

标签: python-3.x upload cherrypy


【解决方案1】:

从响应中获取信息很有用。当您发送请求时,您会收到响应。从此响应中,您可以获得有关 HTTP 代码的信息,其中 200 表示正常,400 表示错误请求。这就是您可以在cherrypy 日志中看到的文本:POST /upload HTTP/1.1" 400。要获取更多信息,请使用print(r.text) 打印响应文本

#!/usr/bin/env python
# -*- coding: UTF-8 -*-

import requests

url = 'http://127.0.0.1:9090/upload'
files = {'ufile': open('file.txt', 'rb')}

r = requests.post(url, files=files)

print(r)
print(r.text)

如果您使用上面的代码和下面的代码,它是上传文件到cherrypy服务器的工作示例。

#!/usr/bin/env python
# -*- coding: UTF-8 -*-

import os
import cherrypy

config = {
    'global' : {
        'server.socket_host' : '127.0.0.1',
        'server.socket_port' : 9090,
        'server.thread_pool' : 8,
        'server.max_request_body_size' : 0,
        'server.socket_timeout' : 60
    }
}


class App:

    @cherrypy.expose
    def upload(self, ufile):
        upload_path = os.path.normpath('/path/to/project/data/')
        upload_file = os.path.join(upload_path, ufile.filename)
        size = 0
        with open(upload_file, 'wb') as out:
            while True:
                data = ufile.file.read(8192)
                if not data:
                    break
                out.write(data)
                size += len(data)
        out = '''
length: {}
filename: {}
mime-type: {}
''' .format(size, ufile.filename, ufile.content_type, data)
        return out


if __name__ == '__main__':
    cherrypy.quickstart(App(), '/', config)

将路径 /path/to/project/data/ 替换为适合您项目的路径。

【讨论】:

猜你喜欢
  • 2012-10-06
  • 2015-01-08
  • 1970-01-01
  • 1970-01-01
  • 2013-05-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多