无法初始化flask initdb(Flask Tutorial Step4)

YAL*_*YAL 14 python database flask

教程链接:http://flask.pocoo.org/docs/0.11/tutorial/dbinit/#tutorial-dbinit

我正在关注Flask教程.这是我的python脚本的当前设置.在本教程结束时,我正在尝试初始化数据库.但由于某种原因,我继续得到同样的错误.

# 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()
Run Code Online (Sandbox Code Playgroud)

这是我的命令的输入:

flask initdb
Run Code Online (Sandbox Code Playgroud)

这是输出:

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

Error: No such command "initdb"
Run Code Online (Sandbox Code Playgroud)

vuo*_*bui 9

我想你应该遵循这个:

  1. 编辑flaskr.py文件中的配置或导出FLASKR_SETTINGS指向配置文件的环境变量.

  2. 从项目目录的根目录安装应用程序

    pip install --editable .
    
    Run Code Online (Sandbox Code Playgroud)
  3. 指示烧瓶使用正确的应用程序

    export FLASK_APP=flaskr
    
    Run Code Online (Sandbox Code Playgroud)
  4. 使用以下命令初始化数据库:

    flask initdb
    
    Run Code Online (Sandbox Code Playgroud)
  5. 现在你可以运行flaskr:

    flask run
    
    Run Code Online (Sandbox Code Playgroud)

注意--editable正确安装.我没有看到"." 第一次.


小智 5

正确的表达应为:

export FLASK_APP=flaskr.py
Run Code Online (Sandbox Code Playgroud)

注意:周围没有空格=

以下屏幕截图显示了具有不同envvar FLASK_APP的输出:

屏幕截图


Sam*_*Sam 5

遇到同样的问题,用

python3 -m flask initdb
Run Code Online (Sandbox Code Playgroud)

我必须为教程做所有事情 python -m flask <command>

我猜它与python3而不是python2有关,但我是python的新手,所以不太确定。