This is a very simple http server lib designed to export APIs in python.
The lib is based on tornado.
The latest version is v1.2.3.
pip install http_api_exporter
from http_api_exporter import ApiHttpServer #import the class
def function(): #define the functions you want to export
...
# Then you have two choices to bind the server with functions.
app = ApiHttpServer({"route" : function})
app.start()
# or
app = ApiHttpServer()
app.bind("route", function)
app.start()
# Finally, you have two ways to pass the args.
{ #pass the args as a list named "Input"
Input: [args]
}
{ #pass the args as a dict
arg: value,
arg0: value,
...
}
{ #combine both
Input: [args],
arg0: value,
...
}
Class SimpleApiServer:
- The simplest api server. Designed to easily bind functions to routes' post method.
- __init__(function_dict=None, welcome_page="Python APIs are providing.", debug=False) :
- Initialize the class.
- function_dict : A dictionary which is composed by "Route" as keys and functions as values.
- welcome_page : A string that allow you modify the welcome page, which can be visited at the root route('\').
- debug : Enable debug log stdout, default is
False
.
- Initialize the class.
- bind(self, route=None, function=None, dictionary=None) :
- Bind the function.
- route : The route to call the corresponding function.
- function : The corresponding function.
- dictionary : If "dictionary" is not
None
, then the "route" and the "function" will be ignored. And unfold the dict that keys as routes and values as functions.
- Bind the function.
- add_periodic_task(self, function, interval) :
- Add periodic task to application, task will be execute every
interval
millisecond. This function should be called beforestart()
- function : The task expected to execute.
- interval : The interval between two executions in milliseconds.
- Add periodic task to application, task will be execute every
- start(port=80, retry=0) :
- Start the server.
- port : Choose which port to listen on.
- retry : How many times to retry if the port has been used, default is
0
which means no retry.
- Start the server.
- __init__(function_dict=None, welcome_page="Python APIs are providing.", debug=False) :
Class ApiHttpServer:
- An alias of
SimpleApiServer
because of compatibility, and will be removed in the future(maybe v2.0.0).
from http_api_exporter import ApiHttpServer
def test_function(arg0, arg1):
#do nothing
return {
"a" : 1
}
if __name__ == "__main__":
app = ApiHttpServer({"/test", test_function})
app.start()
# then post url http://localhost/test
Your function must returns a dictionary which could be jsonified or has no returned value.
bind the functions to routes.
support function without return.
support function without parameters.
support pass parameters by "Input" array.
support pass parameters by dictionary form.
support pass parameters by both of the above.
support periodic tasks.
Add a complex server to handle websocket.
anything else if anyone need.