如何使用python中的Falcon将客户端'GET'请求从一个API路由到另一个具有相同端点的另一个API?



我有两个端点相同但URL不同的API。像这样:

API_1 = /takeout/{t_note}
/serve/{t_note}/{m_note}
API_2 = /takeout/{t_note}
/serve/{t_note}/{m_note}

客户端向API_1发送"GET"请求,但不是返回响应,而是路由到API_2并显示API_2的响应,所有逻辑都发生在API_2。客户端认为它与API_2通信,但实际上将请求发送到API_1。因此,在最后,API_1只是一些代理,它只将请求路由到API_2进行响应。

知道如何做到这一点吗?我要找的是:

class TakeOut(object):
def on_get (self, resp, req, t_note:str):
resp.body = json.dumps() # response of API_2 here for endpoint /takeout/{t_note}
# t_note is just a id in string format which sent by the client

也许是这样。我是猎鹰和API的新手。

app2.py:

import falcon

class Api2(object):
def on_get(self, _req, resp, arg1: str):
resp.status = falcon.HTTP_200 if arg1 == '200' else falcon.HTTP_400
resp.media = {'arg': arg1}

app = falcon.API()
api2 = Api2()
app.add_route('/api2/{arg1}', api2)

app1.py:

import falcon
import requests

class Api1(object):
def on_get(self, _req, resp, arg1: str):
api2_resp = requests.get(f'http://127.0.0.1:8000/api2/{arg1}')
resp.status = falcon.HTTP_200 if api2_resp.status_code == 200 else falcon.HTTP_400
dic = api2_resp.json()
dic["api1"] = 'payload'
resp.media = dic

app = falcon.API()
api1 = Api1()
app.add_route('/api1/{arg1}', api1)

gunicorn app2:app

gunicorn -b '127.0.0.1:8001' app1:app

CCD_ 3=>HTTP/1.1 200 OK ... {"arg": "200", "api1": "payload"}

CCD_ 5=>HTTP/1.1 400 Bad Request ... {"arg": "201", "api1": "payload"}

相关内容

  • 没有找到相关文章

最新更新