In web development term, a handler is a callable object attached to a route, it could be a function, a class, or anything able to be called. This handler will be automatically called  when user click that route. In our case, a handler that is a function named home is attached to the root application route “/” . As the result, when the application is running, if we open the browser to get into the root application having the uri “/”, the handler named home attached to this route will be called resulting the sentence “Welcome to Khmer Web Sanic!” is written on the browser.

 

#routes/front/index.py
from sanic import Sanic
from sanic.response import text

app = Sanic.get_app('Khmerweb')

@app.route("/")
async def home(req):
    return text("Welcome to Khmer Web Sanic!")

 

In Sanic web framework, a handler is a callable object of which the first parameter is to receive request object from the framework and has an obligation to return a response object in Sanic framework to the endpoint. In our case, the handler home has “req” parameter to receive the request object from Sanic framework by responding “text” object to the endpoint. The response object “text” is imported from sanic.response class in Sanic framework. 

 

If we want to return HTML content to the endpoint or the browser, we should import “html” object from sanic.response class.

 

#routes/front/index.py
from sanic import Sanic
from sanic.response import html

app = Sanic.get_app('Khmerweb')

@app.route("/")
async def home(req):
    return html("<b>Welcome to Khmer Web Sanic!</b>")

 

Moreover, we have the choice to define the handler as asynchronous or synchronous by using “async” keyword before the handler's name. However, the handler could run faster if we define it as asynchronous function.