15

Tutorial link: http://flask.pocoo.org/docs/0.11/tutorial/dbinit/#tutorial-dbinit

I am following the Flask tutorial. This is the current setup of my python script. At the end of the tutorial, I am trying to initialize the database. But for some reason, I kept on getting the same error.

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

# create our little application :)
app = Flask(__name__)
app.config.from_object(__name__)

# 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 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.'


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()

This is the input of my command:

flask initdb

This is the output:

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

Error: No such command "initdb"
4
  • 2
    Did you export the flask app as described here? Commented Nov 19, 2016 at 19:14
  • Yes, I did it in this step: flask.pocoo.org/docs/0.11/tutorial/setup/#tutorial-setup Commented Nov 19, 2016 at 19:37
  • 8
    try using export FLASK_APP=flaskr/flaskr.py and then flask initdb Commented Mar 1, 2017 at 14:20
  • @tymbark, this is what worked for me, thanks for providing that. Commented Aug 5, 2020 at 4:19

14 Answers 14

9

I think you should follow this:

  1. edit the configuration in the flaskr.py file or export an FLASKR_SETTINGS environment variable pointing to a configuration file.

  2. install the app from the root of the project directory

    pip install --editable .
    
  3. Instruct flask to use the right application

    export FLASK_APP=flaskr
    
  4. initialize the database with this command:

    flask initdb
    
  5. now you can run flaskr:

    flask run
    

Pay attention to install --editable correctly. I don't see the "." the first time.

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

Comments

6

the correct expression should be:

export FLASK_APP=flaskr.py

Note: no spaces around =.

Following screenshot show you outputs with different envvar FLASK_APP :

screenshot

2 Comments

set FLASK_APP=flaskr on Windows
Also note no spaces around = - this was what I was doing wrong.
5

Ran into the same issue, fixed it with

python3 -m flask initdb

I had to do everything for the tutorial with python -m flask <command>

I'm guessing its something to do with python3 instead of python2 but I'm new to python so not super sure.

Comments

2

In my case, following works:

export FLASK_APP=flaskr.flaskr

flask initdb

Comments

2

The issue could also be the __init.py__ being located in the root folder. vuongbui's answer is the correct one given that __init.py__ is located in flaskr/flaskr and not the root.

Comments

1

You need to stop the current session of flask if it is still running. This is how I solved my problem.

Comments

1

I had this same issue -- what worked for me was re-running the command below in my current shell session.

pip install --editable .

Comments

1

I also had this problem when trying to add the example command to my project, but it was because my Flask command was not in the same file as my main application - I was trying to put it in its own standalone file.

When I put it into my main application file (would be flaskr.py in the questioner's example) then flask finds it.

I then tried to achieve the same end (command in a separate file) using Blueprints but unfortunately commands in Blueprints are not supported yet.

Comments

0

I resolved by looking at the documentation here: http://flask.pocoo.org/docs/1.0/tutorial/database/

click.command() 

defines a command line command called "init-db"

After I saw this I ran the flask init-db command it I got the "Initialized the database" return.

Comments

0

I tried doing the tutorial as well, and ran into this issue.

I'm not sure if there was a change in Flask, but per their instructions, the main Python file is named __init__.py. In order for me to successfully run init-db, I had to do export FLASK_APP=__init__.py. My folder directory was called pythonflask, but when I tried doing export FLASK_APP=pythonflask (per their instructions of calling the directory flaskr and then doing export FLASK_APP=flaskr), I was running into the issue. However, doing export FLASK_APP=__init__.py allowed me to run flask init-db.

Hope this helps!

EDIT: Something I played around with and realized is that I was trying to use my root folder as the FLASK_APP. Once I created a NEW directory in my root directory, I was able to export THAT directory. My folder structure looks like this now:

pythonflask (root)
    |
     app
        __init__.py

Now when I do export FLASK_APP=app, I'm able to run flask init-db with no problem.

Comments

0

I had the same exact issue, following the tutorial exactly. I had run export FLASK_APP=flaskr. To run flask init-db, navigate to the directory above flaskr (for the case of the tutorial, flask-tutorial).

When I run tree (and pare down the cache and hello files from the tutorial), I get:

.
├── flaskr
│   ├── __init__.py
│   ├── db.py
│   └── schema.sql
└── instance
    └── flaskr.sqlite

Where I'm running flask init-db in ..

Comments

0

I know this is old but just for those still having this issue like I did yesterday.

My problem was __init__.py I did not put this tutorial code right before return app:

from . import db
db.init_app(app)

Comments

0

It didn't require me to install editable. Just set the FLASK_APP as the folder which holds the __init__.py file, meaning set the evironment variable as the folder which contains the __init__.py file. In my case, the flask folder holds the flaskr folder which contains the __init__.py file. So, I just did the following

export FLASK_APP=flaskr

Comments

0

Close the server in case you are already running your server. set these things:

export FLASK_APP=flaskr
export FLASK_ENV=development
flask init-db

and make sure to do it in the parent folder of flaskr folder i.e. parent folder of your flask app

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.