简体   繁体   English

将请求转发给 Python (Rust) Robyn 中的另一个 API

[英]Forwarding a request to another API in Python (Rust) Robyn

I am using FastAPI to take in a JSON file which will then be the body of an API request out.. Orwell and Good so far.我正在使用 FastAPI 接收一个 JSON 文件,该文件将成为 API 请求的主体。到目前为止,Orwell 和 Good。 Now I want to apply the same but with robyn built on rust, instead of FastAPI.现在我想应用相同的但使用构建在 rust 上的 robyn,而不是 FastAPI。 Not managed to get any joy with calling the API here at the point marked??.在标记为 ?? 的位置拨打 API 时,没有得到任何快乐。

What things do I need to consider (documentation is sparse).我需要考虑什么(文档很少)。 Does robyn cut it alone, or am I missing something? 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)

With FastAPI:使用 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)

The author of Robyn here. Robyn 的作者在这里。 I am unable to understand what you are trying to achieve here.我无法理解您要在这里实现的目标。 However, there is one issue, request["body"] returns a byte string array at the moment.但是,有一个问题, request["body"]此时返回一个字节字符串数组。

You need to alter your code to this:您需要将代码更改为:

import json
@app.post("/yt")
async def json(request):
    body = bytearray(request["body"]).decode("utf-8")
    data = json.loads(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]

This is peculiarity that I am not very fond of.这是我不太喜欢的特点。 We are hoping to fix this within the next few releases.我们希望在接下来的几个版本中解决这个问题。

I hope this helped:D我希望这有帮助:D

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM