Routing in Sanic web framework is almost the same as in Bottle.py and Express.js web frameworks. Generally, we use route method in Sanic application object to define a route connecting to a handler. We could also use HTTP methods GET, POST, PUT, PATCH, DELETE, HEAD, and OPTIONS in Sanic application object to define route calling these HTTP methods. However, the most used HTTP methods are GET and POST, and web developers like to use route( ) method to define all kind of routes by providing HTTP method as the second key/value argument to this route( ) method. If we do not provide any HTTP method as the second key/value argument, the route( ) method will use HTTP GET method as the second key/value argument.
#routes/front/index.py
from sanic import Sanic
from sanic.response import html
app = Sanic.get_app('Khmerweb')
@app.route("/", methods=["GET","POST"])
async def home(req):
return html('Welcom to Khmer Web Sanic!')
In mathematics, we hear a lot about “parameter” in linear and second degree equation. In fact, parameter plays a crucial role in changing the value in an equation. Likewise, we can also define route with parameter in Sanic web framework by putting parameter in between this sign “< >”.
#routes/front/index.py
from sanic import Sanic
from sanic.response import html
app = Sanic.get_app('Khmerweb')
#http://localhost:8000/1234
@app.route("/<id>")
async def home(req,id):
return html(f'This route has {id} as parameter.')
Route parameter could be an object of the type str, int, float, uuid, regex etc. However, if we want to declare our route parameter as an object of a precise type, we must put the type on its right side. Doing so, all parameters that are not of the type declare in the route or parameters that are not being able to be converted to that type will not be accepted.
#routes/front/index.py
from sanic import Sanic
from sanic.response import html
app = Sanic.get_app('Khmerweb')
#http://localhost:8000/1234
@app.route("/<id:int>")
async def home(req,id):
return html(f'This route has {id} as parameter.')
We have to be careful that route parameter and query parameter are two different things. Query parameter is sent to the handler using “?” and “&” signs after the route path while route parameter is sent to the handler as a part of the route path.
On the other hand, in Sanic web framework, to be able to use static files, we need to manually create a folder for those files and define the route to that folder using static( ) method in Sanic application object. Conventionally, the name for static file folder is “public” or “static”.
#routes/front/index.py
from sanic import Sanic
from sanic.response import html
app = Sanic.get_app('Khmerweb')
app.static("/static", "static")
@app.route("/")
async def home(req):
return html(f'<img src="/static/site_logo.png" />')