HTTP endpoints
HTTP requests and responses
Note that return values from HTTP requested functions will be used to build a HTTP response.
See the example service after the decorator descriptions for a reference implementation of how the invoked functions may be used.
Invoker functions for HTTP services
@tomodachi.http(method, url, ignore_logging=[200])
Sets up an HTTP endpoint for the specified method (GET
, PUT
, POST
, DELETE
) on the url
path (regexp).
Optionally, specify ignore_logging
as a dict
or tuple
containing the status codes to omit from log output – can also be set to True
to ignore everything except status code 500
.
Keep-alive connections can be enabled by setting the options.http.keepalive_timeout
configuration option. Read more about the keep-alive functionality under the "Options / config parameters" section.
@tomodachi.http_static(path, url)
Sets up an HTTP endpoint for static content available as GET
/ HEAD
from the path on disk on the base url
(regexp).
@tomodachi.websocket(url)
Sets up a websocket endpoint on the url
path (regexp). The invoked function is called upon websocket connection and should return a two-valued tuple
containing callables – (first) a function receiving frames and (secondly) a function called on websocket close.
The arguments passed to the decorated function upon connection, beside self
, is the websocket connection object which can be used to send frames to the client, and optionally also the request object to be able to read headers, etc.
@tomodachi.http_error(status_code)
A function which will be called if an HTTP request would result in a 4XX
status response. You may use this for example to set up a custom handler on 404 Not Found
or 403 Forbidden
responses.
Example implementation (HTTP)
import tomodachi
class Service(tomodachi.Service):
name = "http-example"
# Request paths are specified as regex for full flexibility
@tomodachi.http("GET", r"/resource/(?P<id>[^/]+?)/?")
async def resource(self, request, id):
# Returning a string value normally means 200 OK
return f"id = {id}"
@tomodachi.http("GET", r"/health")
async def health_check(self, request):
# Return can also be a tuple, dict or even an aiohttp.web.Response
# object for more complex responses - for example if you need to
# send byte data, set your own status code or define own headers
return {
"body": "Healthy",
"status": 200,
}
# Specify custom 404 catch-all response
@tomodachi.http_error(status_code=404)
async def error_404(self, request):
return "error 404"
Updated about 4 years ago