我想将python3客户端的文件POST到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"
答案 0 :(得分:3)
从响应中获取信息非常有用。发送请求时,您会收到回复。从此响应中,您可以获得有关HTTP代码的信息,其中200表示正常,400表示错误请求。这是你可以在你的日志中看到的文字: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/
替换为适合您项目的路径。