按照flask Tutorial 0.11.x中的步骤操作,出现错误?

根据官方文档,在flask 0.11.x中出现了cli.command这种装饰器

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

此时在命令行中设置了FLASK_APP=flaskr后(flaskr为app的名字),输入设置好的命令就可以直接执行函数,官方示例如下

>flask initdb
Initialized the database.

可是我自己操作的时候就会出现

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

Error: No such command "initdb".

而当我使用另一种操作方法就能成功


>python -m flask initdb
Initialized the database.

在官方文档(http://flask.pocoo.org/docs/0.11/cli/)中这样提到过这个使用方法

After installation of Flask you will now find a flask script installed into your virtualenv. If you don’t want to install Flask or you have a special use-case you can also use python -m flask to accomplish exactly the same.

我在Windows、Ubuntu上分别测试过python3.5、python2.7.11,均出现同样情况

现在我想知道为什么flask initdb这种用法不能成功?

=============================================
源码如下

flaskr.py:

# 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 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__':
    app.run()
阅读 8.1k
4 个回答
新手上路,请多包涵

我在按照1.0教程走的时候也遇到了这个问题
在flaskr文件夹下使用flask init-db命令运行会报错

Error: No such command "initdb".

解决方法是,在flaskr上层文件夹(flask-tutorial)下使用flask init-db命令。

附文件夹结构:

/home/user/Projects/flask-tutorial
├── flaskr/
│   ├── __init__.py
│   ├── db.py
│   ├── schema.sql
│   ├── auth.py
│   ├── blog.py
│   ├── templates/
│   │   ├── base.html
│   │   ├── auth/
│   │   │   ├── login.html
│   │   │   └── register.html
│   │   └── blog/
│   │       ├── create.html
│   │       ├── index.html
│   │       └── update.html
│   └── static/
│       └── style.css
├── tests/
│   ├── conftest.py
│   ├── data.sql
│   ├── test_factory.py
│   ├── test_db.py
│   ├── test_auth.py
│   └── test_blog.py
├── venv/
├── setup.py
└── MANIFEST.in

1、python xxx.py
2、python -m xxx.py
这是两种加载py文件的方式:

1叫做直接运行, 你用flask xxx,就属于这种方式;

2相当于import,叫做当做模块来启动。

不同的加载py文件的方式,会影响——sys.path 这个属性。
使用python -m xxx的方式,你注意系统路径会多出一个'',python解释器就能够在当前路径下找到你“注册”的命令了!
图片描述
参考:http://www.tuicool.com/articles/jMzqYzF

问题已解决,原因是flaskr.py被放在virtualenv文件夹中的flaskr文件夹下。
将文件移至上级文件夹即可解决。

新手上路,请多包涵

之所以出现这个问题,是因为没有正确设置环境变量FLASK_APP.
正确的设置方法为:export FLASK_APP=flaskr
然后再执行:flask init-db

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题