我如何将Args和Kwargs传递到使用FastAPI构建的休息端点?
我正在使用FastAPI构建REST API。目标是通过网络运行Python功能并返回结果。
请注意,我可以修改客户端&服务器代码。
在高级别上,代码是:
@app.post('/my_endpoint')
def serve_data(q:dict):
return foo(*q.get('args', []), **q.get('kwargs', {}))
其中foo是一些复杂的python函数,它具有大量的args&夸尔格斯。
在客户端,我正在使用:
def get_data(endpoint:str='my_endpoint', args:list=None, kwargs:dict=None)->pd.DataFrame:
q = dict(
args = args if args else [],
kwargs = kwargs if kwargs else {}
)
qj = json.dumps(q)
response = requests.post(url = f'http://my_url/{endpoint}', data=qj)
data = response.json()
df = pd.read_json(data)
return df
代码有效,但我不喜欢使用显式args和kwargs调用get_data
。
例如。
get_data(args=['A', 19, 99], kwargs={'date': '2021-01-01', 'font_size': 2})
我希望能够将args和kwargs“传递”到get_data
一直到foo
。
上面的代码将成为:
get_data('A', 19, 99, date='2021-01-01', font_size=2)
# ie. the same signature as `foo`
# On the server this is run:
# foo('A', 19, 99, date='2021-01-01', font_size=2)
有什么想法吗?
I am building a REST api using FastAPI. The goal is to run a python function over the network and return the result.
Note that I CAN modify the client & the server code.
At a high level the code is:
@app.post('/my_endpoint')
def serve_data(q:dict):
return foo(*q.get('args', []), **q.get('kwargs', {}))
Where foo is some complex Python function that takes a very large amount of args & kwargs.
And on the client side I am using:
def get_data(endpoint:str='my_endpoint', args:list=None, kwargs:dict=None)->pd.DataFrame:
q = dict(
args = args if args else [],
kwargs = kwargs if kwargs else {}
)
qj = json.dumps(q)
response = requests.post(url = f'http://my_url/{endpoint}', data=qj)
data = response.json()
df = pd.read_json(data)
return df
The code works, but I don't like having to call get_data
using explicit args and kwargs.
eg.
get_data(args=['A', 19, 99], kwargs={'date': '2021-01-01', 'font_size': 2})
I'd like to be able to "pass" the args and kwargs into get_data
all the way down to foo
.
The code above would become:
get_data('A', 19, 99, date='2021-01-01', font_size=2)
# ie. the same signature as `foo`
# On the server this is run:
# foo('A', 19, 99, date='2021-01-01', font_size=2)
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以简单地定义您的功能:
You can simply define your function like this: