Python使用web.py从POST请求中提取二进制文件 [英] Python Extracting binary from a POST request using web.py

查看:2523
本文介绍了Python使用web.py从POST请求中提取二进制文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am developing an API that allows outside clients to send a binary file which will be processed. my web.data() is a string and the function I am calling requires a binary. How do I get it into the correct format? Maybe I have the incorrect Headers? how do I extract the binary data. I am using web.py.

----------------- POST请求--------- -------------------------------------------

-----------------POST request----------------------------------------------------

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函数------------------ ------------

-----------------------API function------------------------------

  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()

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

------------------------Traceback--------------------------------

  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'

谢谢

很抱歉,如果格式化在帖子中搞砸了。

Sorry if the formatting got all messed up in the Post.

推荐答案

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

Even if it is a binary file, reading raw post data would get you a encoded string. You would need to decode to convert to binary data. You can write to a file as follows:

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

这篇关于Python使用web.py从POST请求中提取二进制文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆