In the api directory of your project root, add the @api decorator to your method. Once the service is started, the endpoint can be accessed at /api/add.
from ab.utils import logger
from ab.utils.algorithm import algorithm
from ab import app
@api()
def add(a, b):
logger.warning("enter algorithm {}, {} ".format(a, b))
return a + bBy default, all endpoints return data in the following structure: {"code": 0, "data": xxx}.
If you want a custom response format, you can return a flask.Response object directly, and the framework will not alter it.
To return a binary file:
from flask import make_response
response = make_response(YOUR_CONTENT)
response.headers['Content-Type'] = 'application/octet-stream'
response.headers['Content-Disposition'] = f'attachment; filename={YOUR_FILENAME}'
return response- The framework provides a default exception class. Common usage is shown below:
from ab.utils.exceptions import AlgorithmException
try:
1 / 0
except Exception as e:
# "from e" must be included to avoid losing the exception stack in logs
raise AlgorithmException(code=-100, data=YOUR_MSG) from eWith this, the client will receive the following response:
{
"code": -100,
"data": "YOUR_MSG"
}- If an uncaught exception is thrown, the client will receive:
{
"code": -1,
"data": "Exception Stack Trace"
}For more information, see Exception and Error Handling.