Neil Patel
Neil Patel

Reputation: 17

Python Flask: Unable to Initialize SQLite Database

I'm following the Flask tutorial found here: http://flask.pocoo.org/docs/0.12/tutorial/. I've followed Steps 0-4 but can't understand Step 5 (Creating the Database); I've read and added the relevent functions to my flaskr.py script, so that it currently looks like this:

# all the imports
import os
import sqlite3
from flask import Flask, request, session, g, redirect, url_for, abort, render_template, flash

app = Flask(__name__) # create the application instance :)
app.config.from_object(__name__) # load config from this file , flaskr.py

# Load default config and override config from an environment variable
app.config.update(dict(
    DATABASE=os.path.join(app.root_path, 'flaskr.db'),
    SECRET_KEY='development key',
    USERNAME='admin',
    PASSWORD='default'
))
app.config.from_envvar('FLASKR_SETTINGS', silent=True)

def connect_db():
    """Connects to the specific database."""
    rv = sqlite3.connect(app.config['DATABASE'])
    rv.row_factory = sqlite3.Row
    return rv

def get_db():
    """Opens a new database connection if there is none yet for the
    current application context.
    """
    if not hasattr(g, 'sqlite_db'):
        g.sqlite_db = connect_db()
    return g.sqlite_db

@app.teardown_appcontext
def close_db(error):
    """Closes the database again at the end of the request."""
    if hasattr(g, 'sqlite_db'):
        g.sqlite_db.close()

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

@app.cli.command('initdb')
def initdb_command():
    """Initializes the database."""
    init_db()
    print('Initialized the database.')

if __name__ == '__main__':
    init_db()
    app.run()

The tutorial then says that the database can be initialized by calling:

flask initdb

Running this command yields:

Usage: flask [OPTIONS] COMMAND [ARGS]...

Error: No such command "initdb".

From following the tutorial thus far, I don't have a flask script in my application directory. I've also done some more reasearch and found this resource: http://flask.pocoo.org/docs/0.12/cli/, which states that a virtual environment comes with this flask script, but my virtual environment doesn't have this file. I've verified this by navigating to my root directory and using:

find . -name flask
find . -name flask.py

However, neither of these commands returns any matches. As I am relatively new to Flask, I might be missing something simple here; can someone explain what I am missing and offer workarounds? Thanks in advance!

Upvotes: 1

Views: 3314

Answers (3)

Larry Tooley
Larry Tooley

Reputation: 11

I received the same error as I worked through the tutorial. I found that I had opened a new terminal window to work in why the server ran in another. I fixed the issue by running the export command again:

export FLASK_APP=flaskr

Then:

flask initdb

Upvotes: 1

Andrew Feierman
Andrew Feierman

Reputation: 128

Try this:

python -m flask initdb

Another thing to check, if you're going through the tutorial: is your __init__.py file in the correct location? It should be in the second level flaskr directory, not in the top-level directory.

Upvotes: 0

skytreader
skytreader

Reputation: 11707

Pure educated guesswork here. But in the code you've shown you have the following:

@app.cli.command('initdb')
def initdb_command():
    """Initializes the database."""
    init_db()
    print('Initialized the database.')

I think that should be

@app.cli.command()
def initdb():
    ...

Notice that there is no argument to the decorator and that the function was renamed to match the command you are invoking in the command line.

A cursory glance at the Flask and click docs does not show that you can pass a string to the decorator and invoke it as labeled.

Upvotes: 1

Related Questions