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?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
You can simply define your function like this:
def get_data(endpoint:str='my_endpoint', *args, **kwargs)->pd.DataFrame:
q = dict(
args = list(args) if args else [],
kwargs = kwargs if kwargs else {}
)
...
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0