【发布时间】:2021-02-05 20:19:15
【问题描述】:
我是 Flask 新手,正在从官方教程中学习,我刚刚设置了我的 sqlite 数据库和模板。问题是当我在设置 venv 和 env 变量后运行 flask run 时。它给了我这个错误输出-
P.S - flask-learn 是我的 venv(它很奇怪,以后会设置为 venv)
Traceback (most recent call last):
File "C:\Users\Kakshipth\Documents\coding\py\backend\flask-learn\Lib\site-packages\flask\_compat.py", line 39, in reraise
raise value
File "C:\Users\Kakshipth\Documents\coding\py\backend\flask-learn\Lib\site-packages\flask\cli.py", line 83, in find_best_app
app = call_factory(script_info, app_factory)
File "C:\Users\Kakshipth\Documents\coding\py\backend\flask-learn\Lib\site-packages\flask\cli.py", line 119, in call_factory
return app_factory()
File "C:\Users\Kakshipth\Documents\coding\py\backend\flaskr\__init__.py", line 36, in create_app
db.init_app(app)
AttributeError: module 'flaskr.db' has no attribute 'init_app'
我猜问题出在 __init__.py 或 db.py 模块上,但我完全按照文档所说的做了。我正在从 backend 文件夹(下面的目录结构)运行这些脚本
我猜你可能会喜欢目录结构,所以这里是 -
backend
|
├───flaskr
│ ├───templates
│ │ └───auth
│ └───__pycache__
|
|___flask-learn
这里是__init__.py -
import os
from flask import Flask
def create_app(test_config=None):
# create and configure the app
app = Flask(__name__, instance_relative_config=True)
app.config.from_mapping(
SECRET_KEY='dev',
DATABASE=os.path.join(app.instance_path, 'flaskr.sqlite'),
)
if test_config is None:
# load the instance config, if it exists, when not testing
app.config.from_pyfile('config.py', silent=True)
else:
# load the test config if passed in
app.config.from_mapping(test_config)
# ensure the instance folder exists
try:
os.makedirs(app.instance_path)
except OSError:
pass
from . import auth
app.register_blueprint(auth.bp)
# a simple page that says hello
@app.route('/hello')
def hello():
return 'Hello, !'
from . import db
db.init_app(app)
return app
这里是db.py -
import sqlite3
import click
from flask import current_app, g
from flask.cli import with_appcontext
def get_db():
if 'db' not in g:
g.db = sqlite3.connect(
current_app.config['DATABASE'],
detect_types=sqlite3.PARSE_DECLTYPES
)
g.db.row_factory = sqlite3.Row
return g.db
def close_db(e=None):
db = g.pop('db', None)
if db is not None:
db.close()
def init_db():
db = get_db()
with current_app.open_resource('schema.sql') as f:
db.executescript(f.read().decode('utf8'))
@click.command('init-db')
@with_appcontext
def init_db_command():
"""Clear the existing data and create new tables."""
init_db()
click.echo('Initialized the database.')
【问题讨论】:
标签: python python-3.x sqlite flask