[英]How to route the client 'GET' request from one API to another another API with same end points using Falcon in python?
我有两个端点相同但 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_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
可能是这样的。 我是 falcon 和 API 的新手。
应用程序2.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)
应用程序1.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
curl -i http://127.0.0.1:8001/api1/200
=> HTTP/1.1 200 OK... {"arg": "200", "api1": "payload"}
curl -i http://127.0.0.1:8001/api1/201
=> HTTP/1.1 400 Bad Request... {"arg": "201", "api1": "payload"}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.