python - 按照flask Tutorial 0.11.x中的步骤操作,出现错误?
怪我咯
怪我咯 2017-04-18 09:03:11
0
2
558

根据官方文档,在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()
怪我咯
怪我咯

走同样的路,发现不同的人生

全員に返信(2)
阿神

1. python xxx.py
2. python -m xxx.py
py ファイルをロードするには次の 2 つの方法があります:

1 は直接操作と呼ばれ、フラスコ xxx を使用する場合は、このメソッドに属します。

2 はインポートに相当し、モジュールとして開始すると呼ばれます。

py ファイルをロードするさまざまな方法は、sys.path 属性に影響します。

python -m xxx を使用します。システム パスに余分な '' が存在することに注意してください。これにより、Python インタープリターが現在のパスで「登録された」コマンドを見つけることができるようになります。

参考: http://www.tuicool.com/articles/jMzqYzF

いいねを押す +0
大家讲道理

flaskr.py が virtualenv フォルダー内の flaskr フォルダーの下に配置されたため、問題は解決されました。
問題を解決するには、ファイルを上位のフォルダーに移動します。

いいねを押す +0
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!