Как вызвать API для каждой строки и не делать по запросу на строку?
В каждом заказе есть код страны, а название страны и валюту нужно получить из справочного API. Запрос на каждую строку — это медленно и упирается в ограничения частоты. API принимает до 100 кодов в одном запросе, значит, строки должны ехать группами.
Группировать не обязан ваш скрипт. Пайп, объявивший пакетный режим, получает массив записей в каждой строке, а где резать поток — решает раннер.
Пайп — шаг обработки данных с объявленными входами и выходами; пайплайн соединяет пайпы.
Что понадобится
- Команда
openflange, релиз v0.0.1:bashgo install github.com/openflange/openflange-go/cmd/openflange@v0.0.1 python3вPATH. Используется только стандартная библиотека: через pip ничего ставить не нужно.- Пустой каталог. Создайте в нём файлы, приведённые ниже, точно под этими именами и выполняйте все команды из этого каталога.
- Ни учётной записи, ни ключа. Данные не покидают вашу машину.
Шаги
1. Запустите заглушку API и сохраните вход
fake-api.py — не настоящий сервис: это локальная заглушка на 127.0.0.1:18089, которая отвечает по таблице из шести стран и пишет по строке на запрос в api.log. Она позволяет выполнить рецепт без сети. Первая команда запускает её в фоне.
#!/usr/bin/env python3
"""A LOCAL STAND-IN for a remote API, so the recipe runs offline. Not a real service.
POST /v1/countries {"codes": ["GB", "FR"]}
200 {"results": [{"code": "GB", "name": "United Kingdom", "currency": "GBP"}, ...]}
One result per code, in order; an unknown code gives {"code": ..., "name": null, "currency": null}.
At most 100 codes per request (HTTP 413 beyond that). Listens on 127.0.0.1:18089 only and appends
one line per request to api.log, so you can see how many requests a run made.
"""
import json
from http.server import BaseHTTPRequestHandler, HTTPServer
COUNTRIES = {
"GB": ("United Kingdom", "GBP"), "FR": ("France", "EUR"), "DE": ("Germany", "EUR"),
"JP": ("Japan", "JPY"), "BR": ("Brazil", "BRL"), "US": ("United States", "USD"),
}
MAX_CODES = 100
class Handler(BaseHTTPRequestHandler):
def do_POST(self):
body = json.loads(self.rfile.read(int(self.headers.get("Content-Length", 0))))
codes = body.get("codes", [])
status = 200 if self.path == "/v1/countries" and len(codes) <= MAX_CODES else (413 if len(codes) > MAX_CODES else 404)
results = []
for code in codes if status == 200 else []:
name, currency = COUNTRIES.get(code, (None, None))
results.append({"code": code, "name": name, "currency": currency})
with open("api.log", "a", encoding="utf-8") as log:
log.write(f"POST {self.path} {status} codes={len(codes)}\n")
payload = json.dumps({"results": results}).encode()
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(payload)))
self.end_headers()
self.wfile.write(payload)
def log_message(self, *args): # quiet: api.log is the only log
pass
if __name__ == "__main__":
HTTPServer(("127.0.0.1", 18089), Handler).serve_forever(){"order":1001,"country":"GB","total":120}
{"order":1002,"country":"FR","total":80}
{"order":1003,"country":"JP","total":4300}
{"order":1004,"country":"GB","total":15}
{"order":1005,"country":"XX","total":60}
{"order":1006,"country":"BR","total":210}
{"order":1007,"country":"DE","total":99}
{"order":1008,"country":"US","total":45}python3 fake-api.py > /dev/null 2>&1 & echo $! > api.pid; sleep 1Эта команда ничего не печатает.
2. Напишите пайп
Блок batch в манифесте — весь переключатель: не больше 100 записей в пакете, и ни одна запись не ждёт дольше 200 мс. Разрешения говорят, что скрипт запускает подпроцесс и отправляет данные на один адрес.
---
spec: openflange.org/pipe/v0.1
id: country-lookup-batch
version: 0.1.0
title: Country lookup through an API (Python, batch mode)
description: Adds `countryName` and `currency` to every record by calling an HTTP API once per batch of records instead of once per record.
license: Apache-2.0
keywords: [api, http, enrichment, batch, python, recipe]
maturity: experimental
scope: record
cardinality: one-to-one
batch:
maxItems: 100 # the API accepts at most 100 codes per request
maxWaitMs: 200 # never hold a record back for more than 200 ms
inputs:
records:
description: 'Records with a `country` member holding a two-letter code, e.g. {"order": 1001, "country": "GB"}.'
schema:
format: json-schema
definition: {type: object, required: [country]}
outputs:
records:
description: The same records, in order, with `countryName` and `currency` added (both null when the API does not know the code).
schema:
format: json-schema
definition:
type: object
required: [countryName, currency]
parameters:
url:
type: string
default: "http://127.0.0.1:18089/v1/countries"
description: 'Endpoint that accepts {"codes": [...]} and answers {"results": [...]}, one result per code, in order.'
timeoutSeconds:
type: integer
default: 10
minimum: 1
maximum: 120
description: Time limit for one request. A request that fails or times out fails the run; it is not retried.
implementation:
type: script
language: python
path: lookup.py
permissions:
subprocess: true
network: ["127.0.0.1:18089"]
remoteData: ["127.0.0.1"]
---
# Country lookup through an API (Python, batch mode)
Implements the [OpenFlange](https://openflange.org/) specification.
A Python script (standard library only) in **batch mode**: the runner writes
one JSON array of up to 100 records per line to its standard input, the script
makes **one HTTP request per line** and answers with one JSON array of the
same length.
- `network` and `remoteData`: the `country` member of every record is sent to
the endpoint. With the default `url` that is the stand-in `fake-api.py` on
this machine; point `url` at a real host and the data leaves the machine,
so change both permissions with it.
- A failed request fails the run (`E_RUNTIME`). Nothing is retried and
nothing is dropped.#!/usr/bin/env python3
# SPDX-License-Identifier: Apache-2.0
"""country-lookup-batch: one HTTP request per batch of records.
Batch mode, delivery `lines`: every line on stdin is a JSON array of records
(a batch); every line on stdout is the JSON array of the results, same length,
same order.
"""
import json
import os
import sys
import urllib.request
with open(os.environ["OPENFLANGE_CONFIG"], encoding="utf-8") as f:
PARAMS = json.load(f)["parameters"]
def lookup(codes):
"""One request for the whole batch: {"codes": [...]} -> {"results": [...]}."""
request = urllib.request.Request(
PARAMS["url"], data=json.dumps({"codes": codes}).encode(), method="POST",
headers={"Content-Type": "application/json"})
with urllib.request.urlopen(request, timeout=PARAMS["timeoutSeconds"]) as response:
results = json.load(response)["results"]
if len(results) != len(codes):
raise ValueError(f"the API answered {len(results)} results for {len(codes)} codes")
return results
for line in sys.stdin:
batch = json.loads(line)
try:
results = lookup([record.get("country") for record in batch])
except (OSError, ValueError, KeyError) as error:
print(f"country-lookup-batch: request failed: {error}", file=sys.stderr)
sys.exit(1)
out = [{**record, "countryName": result["name"], "currency": result["currency"]} for record, result in zip(batch, results)]
sys.stdout.write(json.dumps(out, ensure_ascii=False, separators=(",", ":")))
sys.stdout.write("\n")
sys.stdout.flush() # one answer per batch: the runner waits for it3. Запустите
Три разрешения — по одному на каждое, о котором просит манифест. Затем посмотрите журнал заглушки.
openflange run . --grant subprocess --grant network=127.0.0.1:18089 --grant remoteData=127.0.0.1 < orders.ndjson{"order":1001,"country":"GB","total":120,"countryName":"United Kingdom","currency":"GBP"}
{"order":1002,"country":"FR","total":80,"countryName":"France","currency":"EUR"}
{"order":1003,"country":"JP","total":4300,"countryName":"Japan","currency":"JPY"}
{"order":1004,"country":"GB","total":15,"countryName":"United Kingdom","currency":"GBP"}
{"order":1005,"country":"XX","total":60,"countryName":null,"currency":null}
{"order":1006,"country":"BR","total":210,"countryName":"Brazil","currency":"BRL"}
{"order":1007,"country":"DE","total":99,"countryName":"Germany","currency":"EUR"}
{"order":1008,"country":"US","total":45,"countryName":"United States","currency":"USD"}
completed in 120ms — records: 8 recordscat api.logPOST /v1/countries 200 codes=8Восемь записей, один запрос.
4. Уменьшите пакеты
--batch 3 снижает размер пакета для этого запуска: три запроса по 3, 3 и 2 кода, дописанные в тот же журнал. На выходе те же восемь записей.
openflange run . --grant subprocess --grant network=127.0.0.1:18089 --grant remoteData=127.0.0.1 --batch 3 --output records=enriched.ndjson < orders.ndjsoncompleted in 75ms — records: 8 recordscat api.logPOST /v1/countries 200 codes=8
POST /v1/countries 200 codes=3
POST /v1/countries 200 codes=3
POST /v1/countries 200 codes=25. Протестируйте, затем остановите заглушку
Тестам нужна работающая заглушка. Один из них фиксирует размер пакета в одну запись и ожидает тот же вывод: пайп в пакетном режиме не должен зависеть от того, где разрезан его вход.
# requires: python3, and fake-api.py listening on 127.0.0.1:18089 (start it first)
spec: openflange.org/test/v0.1
pipe: ..
tests:
- name: adds the country name and the currency to every record
grants: {subprocess: true, network: ["127.0.0.1:18089"], remoteData: ["127.0.0.1"]}
inputs:
records:
values:
- {order: 1, country: GB}
- {order: 2, country: JP}
expect:
outputs:
records:
values:
- {order: 1, country: GB, countryName: United Kingdom, currency: GBP}
- {order: 2, country: JP, countryName: Japan, currency: JPY}
- name: an unknown code is kept, with nulls
grants: {subprocess: true, network: ["127.0.0.1:18089"], remoteData: ["127.0.0.1"]}
inputs:
records:
values: [{order: 3, country: XX}]
expect:
outputs:
records:
values: [{order: 3, country: XX, countryName: null, currency: null}]
- name: the same output with one record per request
grants: {subprocess: true, network: ["127.0.0.1:18089"], remoteData: ["127.0.0.1"]}
batch: {maxItems: 1, maxWaitMs: 0}
inputs:
records:
values:
- {order: 1, country: GB}
- {order: 2, country: JP}
expect:
outputs:
records:
values:
- {order: 1, country: GB, countryName: United Kingdom, currency: GBP}
- {order: 2, country: JP, countryName: Japan, currency: JPY}
- name: an endpoint that does not answer fails the run
grants: {subprocess: true, network: ["127.0.0.1:18089", "127.0.0.1:9"], remoteData: ["127.0.0.1"]}
parameters: {url: "http://127.0.0.1:9/v1/countries", timeoutSeconds: 2}
inputs:
records:
values: [{order: 1, country: GB}]
expect:
status: failed
error: {code: E_RUNTIME}
- name: without the grants the pipe is refused before anything is sent
inputs:
records:
values: [{order: 1, country: GB}]
expect:
status: failed
error: {code: E_PERMISSION}openflange test .tests/country-lookup-batch.test.yaml
ok adds the country name and the currency to every record
ok an unknown code is kept, with nulls
ok the same output with one record per request
ok an endpoint that does not answer fails the run
ok without the grants the pipe is refused before anything is sent
ok 5 tests passed in 1 file (333ms)kill $(cat api.pid)Эта команда ничего не печатает.
Ограничения
- API — заглушка. Настоящий сервис не вызывался. Для настоящего измените
urlи оба разрешения (network,remoteData) — и данные каждой записи покинут вашу машину. - Нет повторов, пауз между попытками, ограничения частоты и аутентификации. Запрос, который не удался или превысил время ожидания, завершает запуск с ошибкой. Ключ API был бы объявленным секретом (
permissions.secrets), а не параметром; здесь это не показано. - Запросы идут последовательно: один пакет за раз.
- Пакет — единица передачи, а не группа со смыслом. Раннер режет поток по
maxItemsиmaxWaitMs;--batchможет только уменьшить объявленные значения. - Пайп работает один к одному: в каждом ответе должно быть ровно столько элементов, сколько в пакете.
- Этот раннер не изолирует подпроцессы: разрешение
networkпроверяется до запуска, но не ограничивает процесс Python. - Пакетный режим описан в RFC 0003 и объяснён на странице «Пакетный режим».
Связанные страницы
- В этом рецепте нет стандартных пайпов: это один собственный пайп.
- Концепции, на которых он построен: Пакетный режим, Разрешения
- Собираете это с помощью ИИ-агента? Дайте ему руководство для агентов: правила, раскладку файлов и команды, которыми он проверит собственную работу.
Все команды на этой странице выполнены в Linux с openflange 0.0.1 (go1.27.1 linux/amd64), собранным из коммита 11cf8cc5378d70858724b16aa937d7f3b98c085d репозитория openflange-go. Файлы и записанный вывод хранятся в репозитории сайта в каталоге sites/dev/test/fixtures/recipes/api-per-row-batch/, и тест побайтно сравнивает с ними эту страницу.