2012-06-21 52 views
0

我正在開發一個API,允許外部客戶端發送將要處理的二進制文件。我的web.data()是一個字符串,我調用的函數需要一個二進制文件。我如何將它變成正確的格式?也許我有不正確的標題?我如何提取二進制數據。我正在使用web.py.Python使用web.py從POST請求中提取二進制

----------------- POST請求--------------------------- -------------------------

import json 
import requests 



files = {'file':('000038fe4b46c210c37bdde767835007', open('000038fe4b46c210c37bdde767835007', 'rb'))} 
headers = {'content-type' : 'application/octet-stream', 'X-Auth-Token':'xxxf'} 
r = requests.post('http://XXX:8080/v1/binaries', files = files, headers = header 

------------------ ----- API功能------------------------------

def POST(self): 
       a = web.ctx.env.get("HTTP_X_AUTH_TOKEN", None) 
       creds = authenticator(a) 
       postdata = web.data().read() 
       analysis = atklite.FileAnalysis(data=postdata) 
       metadata = analysis.return_analysis() 

------ - - - - - - - - - 追溯 - - - - - - - - - - - - - - - - -

File "/usr/lib/pymodules/python2.7/web/application.py", line 242, in process 
    return self.handle() 
    File "/usr/lib/pymodules/python2.7/web/application.py", line 233, in handle 
    return self._delegate(fn, self.fvars, args) 
    File "/usr/lib/pymodules/python2.7/web/application.py", line 415, in _delegate 
    return handle_class(cls) 
    File "/usr/lib/pymodules/python2.7/web/application.py", line 390, in handle_class 
    return tocall(*args) 
    File "/home/XXXXXX/ProcessingCode/bfsapi.py", line 75, in POST 
    postdata = web.data().read() 
AttributeError: 'str' object has no attribute 'read' 

謝謝

對不起,如果格式得到了所有雜亂的帖子。

+0

web2py是黑暗的魔法。 –

+2

這個問題似乎涉及[web.py](http://webpy.org)。 [web2py](http://www.web2py.com/examples/default/index)是一個不同的項目。 – Bryan

回答

0

即使它是一個二進制文件,讀取原始數據會得到一個編碼字符串。您需要解碼才能轉換爲二進制數據。你可以寫如下文件:

written = open('binary.file', 'wb') 
for chunk in rawdata.chunks(): 
     written.write(chunk) 
written.close() 
+1

請問你能回答在你的回答中「rawdata」與問題中的對應關係嗎? – starbugs