Sanic application is created by instantiating Sanic class. Moreover, once created, we can use this application object to store useful object for later use in different modules, especially database connection object. Starting from Sanic version 21.3, we can store useful object in the context object called “ctx” in Sanic app object. We need to do so because some object is very expensive to initiate such as database connection for example - it will take time to connect to some kind of database online.

 

As Python already included SQLite database in its standard library, we will use this database in our Sanic project to store various data as an example for database in general. And to use SQLite database, we do not need to install anything, just import sqlite3 module that is it.

 

#index.py
from sanic import Sanic
from models import setDBcon

app = Sanic('Khmerweb')
app.ctx.mydb = setDBcon.con

from routes.front import index

 

#models/setDBcon.py
import sqlite3

DB_NAME = "models/mydb.db"

con = sqlite3.connect(DB_NAME)

 

#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!")

 

Conventionally, every module relating to database is placed in a separated folder called “models” in the root of Sanic project folder. As the result, up until now, the structure of our Sanic project is as the picture below.

 

 

We already mentioned that Sanic application object could be retrieved anywhere in any module by using get_app method in Sanic class. In the case of our Sanic project, we retrieved Sanic application object in “routes/front/index.py” module with an objective to add route for the root application having the address “/” .