在Falcon REST中解码JSON文件上传

deo*_*eff 1 rest python-3.x python-requests falconframework

我正在尝试解码在我的POST请求中上传的图像文件。

我处理上传的课程文件:

class Images(object):

    def on_post(self, req, resp):
        name = req.stream.read()
        helpers.write_json(resp, falcon.HTTP_200, {
            'name':str(name)
        })
Run Code Online (Sandbox Code Playgroud)

调用API,并添加名称和图像文件。图像名称“ youtried.jpg”与我正在运行的文件“ curl.py”处于同一级别。

url = 'http://localhost/service/images'
files = {
    'name': 'Jon Snow',
    'image': (open('youtried.jpg', 'rb').read())
}

r = requests.post(url, headers={'Content-type': 'multipart/form-data'},files=files)

print (json.loads(r.text))
Run Code Online (Sandbox Code Playgroud)

我也尝试过改变

name = req.stream.read()

name = req.stream.read().decode('utf-8')

name = req.stream.read().decode('utf-16')

让我知道是否有适当的方法可以做到这一点。

Tra*_*umi 5

Falcon本身不支持处理multipart / form-data请求(包括文件上传),因此您将不得不使用第三方插件,例如falcon-multipart

只需使用pip安装它,例如:

pip install falcon-multipart
Run Code Online (Sandbox Code Playgroud)

并将其用作中间件,例如:

from falcon_multipart.middleware import MultipartMiddleware
app = falcon.API(middleware=[MultipartMiddleware()])
Run Code Online (Sandbox Code Playgroud)

然后在Images类中,使用以下命令读取文件或文件名:

image = req.get_param('image')
# Read image as binary
raw = image.file.read()
# Retrieve filename
filename = image.filename
Run Code Online (Sandbox Code Playgroud)

因此,在您的代码上下文中,这是正确且完整的版本:

import falcon
import json

from falcon_multipart.middleware import MultipartMiddleware


class Images(object):

    def on_post(self, req, resp):
        image = req.get_param('image')
        # only if you need the image data
        # raw = image.file.read()
        filename = image.filename
        helpers.write_json(resp, falcon.HTTP_200, {
            'name': filename
        })


app = falcon.API(middleware=[MultipartMiddleware()])
app.add_route('/service/images', Images())
Run Code Online (Sandbox Code Playgroud)

  • 我找到一篇文章来测试上传文件 https://gist.github.com/amirma/fc8179f8bcb27d7e7c556a419490e8dc (2认同)