towhee.functional.mixins.serve.ServeMixin¶
- class towhee.functional.mixins.serve.ServeMixin[source]¶
Bases:
object
Mixin for API serve
Methods
api
Make the DataFrame as callable function
Serve the DataFrame as a RESTful API
- as_function()[source]¶
Make the DataFrame as callable function
- Returns:
a callable function
- Return type:
_type_
Examples:
>>> import towhee >>> with towhee.api() as api: ... func1 = ( ... api.map(lambda x: x+' -> 1') ... .map(lambda x: x+' => 1') ... .as_function() ... )
>>> with towhee.api['x']() as api: ... func2 = ( ... api.runas_op['x', 'x_plus_1'](func=lambda x: x+' -> 2') ... .runas_op['x_plus_1', 'y'](func=lambda x: x+' => 2') ... .select['y']() ... .as_raw() ... .as_function() ... )
>>> with towhee.api() as api: ... func3 = ( ... api.parse_json() ... .runas_op['x', 'x_plus_1'](func=lambda x: x+' -> 3') ... .runas_op['x_plus_1', 'y'](func=lambda x: x+' => 3') ... .select['y']() ... .as_json() ... .as_function() ... )
>>> func1('1') '1 -> 1 => 1' >>> func2('2') '2 -> 2 => 2' >>> func3('{"x": "3"}') '{"y": "3 -> 3 => 3"}'
- serve(path='/', app=None)[source]¶
Serve the DataFrame as a RESTful API
- Parameters:
path (str, optional) – API path. Defaults to ‘/’.
app (_type_, optional) – The FastAPI app the API bind to, will create one if None.
- Returns:
the app that bind to
- Return type:
_type_
Examples:
>>> from fastapi import FastAPI >>> from fastapi.testclient import TestClient >>> app = FastAPI()
>>> import towhee >>> with towhee.api() as api: ... app1 = ( ... api.map(lambda x: x+' -> 1') ... .map(lambda x: x+' => 1') ... .serve('/app1', app) ... )
>>> with towhee.api['x']() as api: ... app2 = ( ... api.runas_op['x', 'x_plus_1'](func=lambda x: x+' -> 2') ... .runas_op['x_plus_1', 'y'](func=lambda x: x+' => 2') ... .select['y']() ... .serve('/app2', app) ... )
>>> with towhee.api() as api: ... app2 = ( ... api.parse_json() ... .runas_op['x', 'x_plus_1'](func=lambda x: x+' -> 3') ... .runas_op['x_plus_1', 'y'](func=lambda x: x+' => 3') ... .select['y']() ... .serve('/app3', app) ... )
>>> client = TestClient(app) >>> client.post('/app1', '1').text '"1 -> 1 => 1"' >>> client.post('/app2', '2').text '{"y":"2 -> 2 => 2"}' >>> client.post('/app3', '{"x": "3"}').text '{"y":"3 -> 3 => 3"}'