我正在跟踪以下位置的Flask教程:http://flask.pocoo.org/docs/0.12/tutorial/。我已经按照步骤0-4进行操作,但无法理解步骤5(创建数据库);我已经阅读了relevent函数并将其添加到flaskr.py脚本中,因此当前看起来像这样:
# 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()
然后,教程说可以通过以下方式初始化数据库:
flask initdb
运行此命令将产生:
Usage: flask [OPTIONS] COMMAND [ARGS]...
Error: No such command "initdb".
到目前为止,按照本教程进行操作之后,我的应用程序目录中没有
flask
脚本。我还进行了一些进一步的搜索,找到了以下资源:http://flask.pocoo.org/docs/0.12/cli/,该资源说明该Flask脚本附带了一个虚拟环境,但是我的虚拟环境没有此文件。我已经通过导航到我的根目录并使用以下命令来验证了这一点:find . -name flask
find . -name flask.py
但是,这些命令都不返回任何匹配项。因为我对Flask不太熟悉,所以这里可能缺少一些简单的东西。有人可以解释我所缺少的内容并提供解决方法吗?提前致谢!
最佳答案
这里纯受过教育的猜测。但是在代码中,您显示出以下内容:
@app.cli.command('initdb')
def initdb_command():
"""Initializes the database."""
init_db()
print('Initialized the database.')
我认为应该是
@app.cli.command()
def initdb():
...
请注意,装饰器没有参数,并且函数已重命名以匹配您在命令行中调用的命令。
粗略浏览一下Flask和click文档,并不表示您可以将字符串传递给装饰器并按标记调用它。
关于python-2.7 - Python Flask:无法初始化SQLite数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41335962/