结合requests的post请求进行cherrypy文件上传
我在用Python的requests库发送POST请求,同时搭配cherrypy服务器上传文件时遇到了麻烦。
这是cherrypy服务器端的代码:
@cherrypy.expose
def upload(self, myFile=None):
out = """<html>
<body>
myFile length: %s<br />
myFile filename: %s<br />
myFile mime-type: %s
</body>
</html>"""
size = 0
allData=''
logging.info('myfile: ' + str(myFile))
while True:
data = myFile.file.read(8192)
allData+=data
if not data:
break
size += len(data)
savedFile=open(myFile.filename, 'wb')
logging.info('writing file: ' + myFile.filename)
savedFile.write(allData)
savedFile.close()
return out % (size, myFile.filename, myFile.type)
而客户端(目前)只是一个简单的Python requests调用: testfile = open('testfile', 'r') request = requests.post("http://:8088/upload/", files={'myFile': testfile})
不幸的是,我对这两个框架的经验不多,所以我在想问题出在哪里。当我执行这个代码时,myFile变量没有被填充(我甚至不确定它是否应该被填充),而且我也不太清楚cherrypy应该如何接收这个文件。任何帮助都非常感谢!
附注:我收到的错误信息:
File "/usr/lib/pymodules/python2.7/cherrypy/_cprequest.py", line 656, in respond
response.body = self.handler()
File "/usr/lib/pymodules/python2.7/cherrypy/lib/encoding.py", line 188, in __call__
self.body = self.oldhandler(*args, **kwargs)
File "/usr/lib/pymodules/python2.7/cherrypy/_cpdispatch.py", line 34, in __call__
return self.callable(*self.args, **self.kwargs)
File "/usr/bin/apt-repo", line 194, in upload
data = myFile.file.read(8192)
AttributeError: 'NoneType' object has no attribute 'file'
10.136.26.168 - - [25/Mar/2013:15:51:37] "POST /upload/ HTTP/1.1" 500 1369 "" "python- requests/0.8.2"
所以我尝试用默认示例来做这个。以下是我对上传方法所做的修改:
@cherrypy.expose
def upload(self, myFile=None):
out = """<html>
<body>
myFile length: %s<br />
myFile filename: %s<br />
myFile mime-type: %s
</body>
</html>"""
# 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)
print out % (size, myFile.filename, myFile.content_type)
return out % (size, myFile.filename, myFile.content_type)
"""
非常基础,直接来自cherrypy的文档。
这是我在客户端所做的:
jlsookiki@justin1:~$ ls -lh bnt-beapi_1.9.6_amd64.deb
-rw-r--r-- 1 jlsookiki users 30K Mar 26 11:20 bnt-beapi_1.9.6_amd64.deb
jlsookiki@justin1:~$ python
>>> import requests
>>> files = open('bnt-beapi_1.9.6_amd64.deb', 'rb')
>>> url = "http://0.0.0.0:8089/upload"
>>> r = requests.post(url, files={'myFile': files})
>>> print r.text
<html>
<body>
myFile length: 0<br />
myFile filename: bnt-beapi_1.9.6_amd64.deb<br />
myFile mime-type: application/x-debian-package
</body>
</html>
出于某种原因,文件实际上没有被发送过来,也没有被读取。有人知道这是为什么吗?
1 个回答
0
确保当你启动服务器时,cherrpy代码有权限写入你想保存文件的地方。