如何使用 Avro 文件发送 http post 请求?

How to send http post request with an Avro file?

我有一个烧瓶 api,它在 Avro 中等待 post 请求。问题是我不确定如何发送 Avro 请求来测试它。 api 使用 fastavro.reader(io.BytesIO(request.data))

读取数据

我试过使用 postman: 在 header 中将 Content-Type 定义为 "avro/binary" 但是看起来不可能 https://github.com/postmanlabs/postman-app-support/issues/4435

我也试过 curl:

curl -X POST -H "Content-Type: avro/binary" --data "{"city": "ALA",
"number_of_points": 42, "transport": "CAR", "subtype": "PURCHASE"}"
"http://localhost:8080/invocations"

然而fastavroreturns出现如下错误:

文件 "fastavro/_read.pyx",第 725 行,在 fastavro._read.file_reader.init

ValueError:无法读取 header - 它是 avro 文件吗?

资源:

https://github.com/fastavro/fastavro

https://avro.apache.org/

好的,根据 fastavro 文档中的 example,我假设您有一个有效的 .avro 文件。

这就变成了一个简单的案例,将其作为标准文件上传到 Flask 进行处理。因此,与其从 request.data 获取数据,不如这样:

from fastavro import reader
from flask import Flask, request
app = Flask(__name__)

# This is really basic and could use some validation
@app.route('/invocations', methods=['POST'])
def upload():
    if request.method == 'POST':
        file = request.files['file']
        for record in reader(file):
                print (record)
        return 'uploaded'

然后您可以使用 curl 将文件提交到端点:

curl -i -X POST -F 'file=@out.avro' "http://localhost:5000/invocations" -H 'ContentType: multipart/form-data'

这应该会在服务器控制台上产生如下内容:

 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
{'station': '011990-99999', 'time': 1433269388, 'temp': 0}
{'station': '011990-99999', 'time': 1433270389, 'temp': 22}

如果您希望使用请求库提交,您可以这样做:

import requests

def upload(filename):
    headers={'ContentType': 'multipart/form-data'}
    with open(filename,'rb') as f:
        files = {'file': f}
        url='http://localhost:5000/invocations'
        r = requests.post(url, files=files)
        print (r.content, r.status_code)

upload('out.avro')