【问题标题】:Python Extracting binary from a POST request using web.pyPython使用web.py从POST请求中提取二进制文件
【发布时间】:2012-06-23 16:12:12
【问题描述】:

我正在开发一个 API,它允许外部客户端发送将被处理的二进制文件。我的 web.data() 是一个字符串,我调用的函数需要一个二进制文件。如何将其转换为正确的格式?也许我的标题不正确?如何提取二进制数据。我正在使用 web.py。

-----------------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'

谢谢

对不起,如果格式在帖子中搞砸了。

【问题讨论】:

  • 这个问题似乎与web.py 有关。 web2py 是一个不同的项目。

标签: python http web.py python-requests


【解决方案1】:

即使是二进制文件,读取原始帖子数据也会得到一个编码字符串。您需要解码才能转换为二进制数据。您可以按如下方式写入文件:

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

【讨论】:

  • 能否请您概述一下答案中的rawdata 与问题中的对应关系?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-09-02
  • 1970-01-01
  • 2017-05-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-15
相关资源
最近更新 更多