我是不熟悉烧瓶的人,并且我正在从官方教程中学习,我只是设置了sqlite
数据库和模板。问题是在设置venv和env变量后运行flask run
时。它给了我这个错误输出-
P.S-flask-learn
是我的命脉(如果它很怪异,将来会设置为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.')
答案 0 :(得分:1)
您的db.py
缺少init_app
功能:
def init_app(app):
app.teardown_appcontext(close_db)
app.cli.add_command(init_db_command)