Reputation: 395
I'm new to flask and i'm learning from the official tutorial, I just set up my sqlite
db and templates. The problem is when i run flask run
after setting venv and env variables. It gives me this error output -
P.S - flask-learn
is my venv(ik its weird, ill set it to venv
in future)
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'
I'm guessing the problem is with __init__.py
or db.py
modules, but i did exactly what the documentation said.And i'm running these scripts from backend
folder(dir structure below)
I'm guessing you might as for directory structure so here it is -
backend
|
├───flaskr
│ ├───templates
│ │ └───auth
│ └───__pycache__
|
|___flask-learn
here is __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
Here is 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.')
link to the official documentation im following
Upvotes: 0
Views: 1643
Reputation: 645
Your db.py
is missing the init_app
-function:
def init_app(app):
app.teardown_appcontext(close_db)
app.cli.add_command(init_db_command)
Upvotes: 2