用Falcon库将图像发布到REST API并收集数据的正确方法是什么? [英] What is the right way to post image to REST API and gather data with Falcon library?

查看:108
本文介绍了用Falcon库将图像发布到REST API并收集数据的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试发布图像以通过我的REST API对其进行处理.我将falcon用于后端,但无法弄清楚如何发布和接收数据.

I try to post an image to process it through my REST API. I use falcon for the backend but could not figure out how to post and receive the data.

这是我当前发送文件的方式

This is how I currently send my file

img = open('img.png', 'rb')
r = requests.post("http://localhost:8000/rec",
files={'file':img},
data = {'apikey' : 'bla'})

但是在Falcon仓库中,他们说Falcon不支持HTML表单发送数据,而是针对POST和PUTed数据的全部范围,我不区分POST图像数据和上面发送的图像.

However at the Falcon repo they say that Falcon does not support HTML forms to send data instead it aims full scope of POSTed and PUTed data which I do not differentiate POSTed image data and the one sent as above.

因此,最终,我喜欢学习正确的解决方法,该方法是发送图像并通过据说由Falcon编写的REST API接收图像.你能给一些指点吗?

So eventually, I like to learn what is the right workaround to send a image and receive it by a REST API which is supposedly written by Falcon. Could you give some pointers?

推荐答案

为此,您可以使用以下方法:

For this you can use the following approach:

Falcon API代码:

Falcon API Code:

import falcon
import base64
import json

app = falcon.API()
app.add_route("/rec/", GetImage())

class GetImage:

    def on_post(self, req, res):

        json_data = json.loads(req.stream.read().decode('utf8'))
        image_url = json_data['image_name']
        base64encoded_image = json_data['image_data']
        with open(image_url, "wb") as fh:
            fh.write(base64.b64decode(base64encoded_image))

        res.status = falcon.HTTP_203
        res.body = json.dumps({'status': 1, 'message': 'success'})

对于API调用:

import requests
import base64

with open("yourfile.png", "rb") as image_file:
    encoded_image = base64.b64encode(image_file.read())

r = requests.post("http://localhost:8000/rec/", 
                  data={'image_name':'yourfile.png',
                        'image_data':encoded_image
                       }
                 )
print(r.status_code, r.reason)

我希望这会有所帮助.

这篇关于用Falcon库将图像发布到REST API并收集数据的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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