1
我很難將python請求發佈請求與cherrypy服務器結合起來以上傳文件。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)
和客戶端(現在)是一個簡單的蟒蛇請求撥打: testfile的=開放(「testfile的」,「R ') request = requests.post(「http://:8088/upload /」,files = {'myFile':testfile})
不幸的是我對這兩個框架沒有太多的經驗,我很想知道錯誤交流在哪裏。當這個被執行時,myFile變量沒有被填充(甚至不知道它是否應該是),我也不確定cherrypy應該如何接收文件。所有幫助表示讚賞!
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的文檔中找到。
這裏是我做的客戶端是什麼:
[email protected]:~$ 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
[email protected]:~$ 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>
出於某種原因,該文件實際上並未得到送過來,並沒有被讀取。任何人都知道爲什麼會發生這種情況?
您的代碼完全適合我。 – 2013-03-26 04:56:25
它呢?你能夠正確地將文件保存在服務器端? – jsookiki 2013-03-26 17:51:10
是的。對不起,我希望我遇到了一個錯誤。 :) – 2013-03-26 20:20:00