1

I have read the Flask documentation and Python documentation to try to understand what these codes do. I know that it is initialise the Database but would like to know in very detail and with normal language, easy language for beginner.

Can anyone please explain me about this?

import sqlite3
from contextlib import closing

DATABASE = 'flaskr.db'

def connect_db():
    return sqlite3.connect(app.config[’DATABASE’])


def init_db():
    with closing(connect_db()) as db:
        with app.open_resource(’schema.sql’, mode=’r’) as f:
            db.cursor().executescript(f.read())
        db.commit()

1 Answer 1

1
import sqlite3

Imports Data base connectors

from contextlib import closing

No idea why its used. Documentetion here

DATABASE = 'flaskr.db'

Defines database,in this case it is a db file.

def connect_db():
    return sqlite3.connect(app.config[’DATABASE’])

Connect DB method which returns a sqlite3 connection, using sqlite3 import and invoking connect() on it. Hint: try >>> dir(sqlite3) after importing in your python console

def init_db():
  with closing(connect_db()) as db:
    with app.open_resource(’schema.sql’, mode=’r’) as f:
        db.cursor().executescript(f.read())
    db.commit()

Initialize database method, it takes a schema.sql and executes it on DB by f.read method. After executing you need to commit changes to db, hence db.commit()

You can find it explained clearly here

Sign up to request clarification or add additional context in comments.

1 Comment

contextlib.closing is used so that init_db can use it rather than the more verbose try: db = connect_db() try: f = app.open_resource(...) # snip finally: f.close() finally: db.close()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.