Request object that is automatically passed to “req” parameter in the handler contains many important information in the context where the request object is passed. Among those objects, query parameters included in the route path in question were extracted and stored in request.args and request.query_args objects. As the result, we have two choices to get those query parameters from one of the two objects.
#routes/front/index.py
from sanic import Sanic
from sanic.response import html
app = Sanic.get_app('Khmerweb')
#http://localhost:8000/?key1=val1&key2=val2&key3=val3
@app.route("/")
async def home(req):
return html(str(req.args))
#routes/front/index.py
from sanic import Sanic
from sanic.response import html
app = Sanic.get_app('Khmerweb')
#http://localhost:8000/?key1=val1&key2=val2&key3=val3
@app.route("/")
async def home(req):
return html(str(req.query_args))
Besides extracting useful query parameters included in the route path, we could also use request object as a place to store necessary information to be used in the same context. In short, we could use request object in the same way as we use Sanic application object to store database connection object earlier.
#routes/front/index.py
from sanic import Sanic
from sanic.response import html
app = Sanic.get_app('Khmerweb')
@app.route("/")
async def home(req):
from models import setDBcon
req.ctx.mydb = setDBcon.con
print(req.ctx.mydb)
return html('Done!')