You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于Rust的Robyn框架实现API请求转发问题求助

Robyn框架实现JSON转发外部API的问题解决

我之前用FastAPI实现了接收JSON数据并转发到外部API的功能,运行正常。现在想换成基于Rust的Robyn框架做同样的事,但在代码里标记??的调用外部API环节卡壳了。Robyn相关文档不多,想知道实现这个功能要注意哪些要点,Robyn能不能单独完成这个需求,是不是我漏了什么?

Robyn原始代码示例

from robyn import Robyn, jsonify

app = Robyn(__file__)

@app.post("/yt")
async def json(request):
    body = request["body"]
    outurl = "https://translate.otherapi.com/translate/v1/translate"
    headers = {
            "Content-Type": "application/json",
            "Authorization": "Bearer {0}".format(TOKEN)
        }
    ?? response_data = await call_api(data)
    return response_data['translations'][0]


app.start(port=5000)

FastAPI实现代码

import aiohttp
import aiofiles
import json
import requests 
from fastapi import FastAPI, Header, Depends, HTTPException, Request

app = FastAPI()

async def call_api(data):
    async with aiohttp.ClientSession(connector=aiohttp.TCPConnector(ssl=False)) as session:
        async with session.post(url, headers=headers, json=data) as resp:
            response_data = await resp.json()
    return response_data

@app.post("/yt")
async def root(request:Request):
    data = await request.json()
    file_path = "data.json"
    await write_json_to_file(data, file_path)
    data = await read_json_from_file(file_path)
    response_data = await call_api(data)
    return response_data['translations'][0]

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8001)

问题分析与解决方案

Robyn本身可以单独完成这个需求,你主要遗漏了以下几个关键要点:

  • 异步HTTP客户端依赖:Robyn框架本身不内置HTTP客户端,需要像FastAPI一样引入aiohttp这类异步HTTP库来实现外部API调用。
  • 请求体解析:Robyn的request["body"]返回的是原始字节数据,需要手动解析为JSON格式,而FastAPI的request.json()已经帮你做了这一步。
  • 变量与函数定义:原始代码中call_api函数未定义,data变量也未赋值,TOKEN需要提前定义,url要对应outurl。

修正后的Robyn代码

import aiohttp
import json
from robyn import Robyn, jsonify

# 替换为你的实际TOKEN
TOKEN = "your_actual_token_here"

app = Robyn(__file__)

async def call_api(data, url, headers):
    async with aiohttp.ClientSession(connector=aiohttp.TCPConnector(ssl=False)) as session:
        async with session.post(url, headers=headers, json=data) as resp:
            # 处理HTTP错误状态码
            if resp.status >= 400:
                raise Exception(f"External API request failed with status {resp.status}")
            response_data = await resp.json()
            return response_data

@app.post("/yt")
async def translate(request):
    # 解析请求体为JSON
    try:
        data = json.loads(request["body"])
    except json.JSONDecodeError:
        return jsonify({"error": "Invalid JSON body"}), 400
    
    outurl = "https://translate.otherapi.com/translate/v1/translate"
    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {TOKEN}"
    }
    
    try:
        response_data = await call_api(data, outurl, headers)
        return jsonify(response_data['translations'][0])
    except Exception as e:
        return jsonify({"error": str(e)}), 500

app.start(port=5000)

额外注意事项

  • 错误处理:加入了JSON解析错误、外部API请求失败的捕获,返回对应的HTTP状态码和错误信息,避免程序崩溃。
  • 异步一致性:确保所有涉及IO的操作(比如HTTP请求)都用异步方式,并正确使用await。
  • 变量作用域:把url和headers作为参数传入call_api,避免全局变量带来的问题。

内容的提问来源于stack exchange,提问作者codervince

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 02:56:52