We already use response object since the beginning of this project by importing it as text or html callable object from sanic.response class. We also know that the handler need response object to send a content to the endpoint or the browser. Besides text and html callable object, we still have a number of other useful objects to use in a variety of context. In fact, we can import json, file, redirect etc to use in the handler if we need them.
If your background is Express.js, you will see that the role of request and response objects in Sanic web framework is almost the same as req and res objects in Express.js. The difference is only response object in Sanic web framework is not passed automatically to the handler as Express.js does, we need to import and use it manually in the handler.
In general, json object in Sanic web framework is used to send content as json object to the endpoint, file object to send file, and redirect to redirect the current route to a different one.
#routes/front/index.py
from sanic import Sanic
from sanic.response import json
app = Sanic.get_app('Khmerweb')
@app.route("/")
async def home(req):
return json({
'username':'Sokhavuth',
'email':'vuthdevelop@gmail.com'
})
#routes/front/index.py
from sanic import Sanic
from sanic.response import redirect
app = Sanic.get_app('Khmerweb')
@app.route("/")
async def home(req):
return redirect('/admin')