我很难将python请求发布请求与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请求调用: testfile = open('testfile','r') request = requests.post(“http://:8088 / upload /”,files = {'myFile':testfile})
不幸的是,我对这两个框架没有太多经验,我想知道错误传达的发生在哪里。执行此操作时,不会填充myFile变量(甚至不确定它是否应该是这样)并且我不确定应该如何接收该文件。感谢所有帮助!
PS。我收到的错误:
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>
由于某种原因,该文件实际上并未被发送并且未被读取。任何人都知道为什么会这样?
答案 0 :(得分:0)
确保在启动服务器时,cherrpy代码具有访问/权限以写入您尝试保存文件的位置。