为了上传文件,我很难将python请求post请求与cherrypy服务器相结合。
下面是cherryypy服务器内部的服务器端代码:
@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')请求=请求。邮报》("http://: 8088/上传/文件= {myFile:测试文件})
不幸的是,我对这两个框架没有太多的经验,我想知道哪里发生了误解。当它被执行时,myFile变量没有被填充(甚至不确定它是否应该被填充),我也不确定cherry应该如何接收这个文件。感谢所有的帮助!
p。我收到的错误:
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)
"""
非常基本的。直接从cherry的文档里来的。
下面是我在客户端所做的:
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>
由于某种原因,文件实际上没有被发送,也没有被读取。有人知道为什么会这样吗?
确保在启动服务器时,cherrpy代码具有访问/权限,可以写入试图保存文件的位置