Build Python Web Apps With Flask FlaskFM project

Hello. I am on the FlaskFM project in the Flask path, on task 13 it says for us to add data to the database using python3 add_data.py and this error occured:

Traceback (most recent call last):
  File "/usr/local/lib/python3.6/dist-packages/sqlalchemy/engine/base.py", line 1228, in _execute_context
    cursor, statement, parameters, context
  File "/usr/local/lib/python3.6/dist-packages/sqlalchemy/engine/default.py", line 587, in do_executemany
    cursor.executemany(statement, parameters)
sqlite3.OperationalError: no such table: playlist

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "add_data.py", line 32, in <module>
    db.session.commit()
  File "/usr/local/lib/python3.6/dist-packages/sqlalchemy/orm/scoping.py", line 162, in do
    return getattr(self.registry(), name)(*args, **kwargs)
  File "/usr/local/lib/python3.6/dist-packages/sqlalchemy/orm/session.py", line 1036, in commit
    self.transaction.commit()
  File "/usr/local/lib/python3.6/dist-packages/sqlalchemy/orm/session.py", line 503, in commit
    self._prepare_impl()
  File "/usr/local/lib/python3.6/dist-packages/sqlalchemy/orm/session.py", line 482, in _prepare_impl
    self.session.flush()
  File "/usr/local/lib/python3.6/dist-packages/sqlalchemy/orm/session.py", line 2496, in flush
    self._flush(objects)
  File "/usr/local/lib/python3.6/dist-packages/sqlalchemy/orm/session.py", line 2637, in _flush
    transaction.rollback(_capture_exception=True)
  File "/usr/local/lib/python3.6/dist-packages/sqlalchemy/util/langhelpers.py", line 69, in __exit__
    exc_value, with_traceback=exc_tb,
  File "/usr/local/lib/python3.6/dist-packages/sqlalchemy/util/compat.py", line 178, in raise_
    raise exception
  File "/usr/local/lib/python3.6/dist-packages/sqlalchemy/orm/session.py", line 2597, in _flush
    flush_context.execute()
  File "/usr/local/lib/python3.6/dist-packages/sqlalchemy/orm/unitofwork.py", line 422, in execute
    rec.execute(self)
  File "/usr/local/lib/python3.6/dist-packages/sqlalchemy/orm/unitofwork.py", line 589, in execute
    uow,
  File "/usr/local/lib/python3.6/dist-packages/sqlalchemy/orm/persistence.py", line 245, in save_obj
    insert,
  File "/usr/local/lib/python3.6/dist-packages/sqlalchemy/orm/persistence.py", line 1083, in _emit_insert_statements
    c = cached_connections[connection].execute(statement, multiparams)
  File "/usr/local/lib/python3.6/dist-packages/sqlalchemy/engine/base.py", line 984, in execute
    return meth(self, multiparams, params)
  File "/usr/local/lib/python3.6/dist-packages/sqlalchemy/sql/elements.py", line 293, in _execute_on_connection
    return connection._execute_clauseelement(self, multiparams, params)
  File "/usr/local/lib/python3.6/dist-packages/sqlalchemy/engine/base.py", line 1103, in _execute_clauseelement
    distilled_params,
  File "/usr/local/lib/python3.6/dist-packages/sqlalchemy/engine/base.py", line 1288, in _execute_context
    e, statement, parameters, cursor, context
  File "/usr/local/lib/python3.6/dist-packages/sqlalchemy/engine/base.py", line 1482, in _handle_dbapi_exception
    sqlalchemy_exception, with_traceback=exc_info[2], from_=e
  File "/usr/local/lib/python3.6/dist-packages/sqlalchemy/util/compat.py", line 178, in raise_
    raise exception
  File "/usr/local/lib/python3.6/dist-packages/sqlalchemy/engine/base.py", line 1228, in _execute_context
    cursor, statement, parameters, context
  File "/usr/local/lib/python3.6/dist-packages/sqlalchemy/engine/default.py", line 587, in do_executemany
    cursor.executemany(statement, parameters)
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table: playlist
[SQL: INSERT INTO playlist (id) VALUES (?)]
[parameters: ((3456,), (2342,), (4576,), (8743,))]
(Background on this error at: http://sqlalche.me/e/e3q8)

Here is my code:
app.py

from flask import Flask, render_template
#import SQLALchemy
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
#set the SQLALCHEMY_DATABASE_URI key
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///song_library.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SECRET_KEY'] = 'you-will-never-guess'
#create an SQLAlchemy object named `db` and bind it to your app
db = SQLAlchemy(app)
#a simple initial greeting
@app.route('/')
@app.route('/index')
def greeting():
    return render_template('greeting.html')

# app name 
@app.errorhandler(404) 
def not_found(e): 
  return render_template("404.html") 

#uncomment the code below here when you are done creating database instance db and models
#import routes

models.py

from app import app, db

#the User model: each user has a username, and a playlist_id foreign key referring
#to the user's Playlist
class User(db.Model):
  id = db.Column(db.Integer, primary_key = True)
  username = db.Column(db.String(50), index = True, unique = True) 
  playlist_id = db.Column(db.Integer,  db.ForeignKey('playlist.id'))
  
  #representation method
  def __repr__(self):
        return "{}".format(self.username)

#create the Song model here + add a nice representation method
class Song(db.Model):
  id = db.Column(db.Integer, primary_key = True)
  artist = db.Column(db.String(40), index = True,unique = False)
  title = db.Column(db.String(70), index = True, unique = False)
  n = db.Column(db.Integer, index = False, unique = False)

  def __repr__(self):
    return "Song name: {}, song title: {}, the song artist is: {}".format(self.name, self.title, self.artist)
#create the Item model here + add a nice representation method
class Item(db.Model):
  id = db.Column(db.Integer, primary_key = True)
  song_id = db.Column(db.Integer, db.ForeignKey('song.id'))
  playlist_id = db.Column(db.Integer, db.ForeignKey('playlist.id'))

  def __repr__(self):
    return "Item name: {}".format(self.name)
#create the Playlist model here + add a nice representation method
class Playlist(db.Model):
  id = db.Column(db.Integer, primary_key = True)
  items = db.relationship('Item', backref='playlist', lazy='dynamic')

This is the key part of your error: sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table: playlist

Check your song_library.db with a program like DB Browser and see if you’ve really created the table “playlist”.

If you didn’t, then you probably need to create one in the terminal either with SQLite3 or SQLAlchemy.

1 Like

Hey @toastedpitabread, I looked on DB Browser, the table is not there. But I am wondering how do I create table in terminal using Flask-SQLAlchemy?

Never mind… I figured out I had to also import the 4 models from the models.py file, but thanks a lot @toastedpitabread.

1 Like

Hm, there’s a couple of ways.

A simple way is

flask shell
from (python file with the db) import db
db.create_all()

#then you can input some items to get started like

song1 = Song(title = "lalala", artist="someone) # + whatever info needed.
db.session.add(song1)

db.session.commit()
1 Like

Oh, I didn’t know about flask shell! What does it do?

It’s optional, but for example it can initialize with a loaded app context.

The flask documentation says it better than I can:

https://flask.palletsprojects.com/en/1.1.x/shell/

@hypercoder457
Miguel Grinberg is a great resource, he has a blog on flask (and a good reference book published by O’Reilley… if you intend to use flask a lot I think it’s valuable to have it). Corey Schafer also has a great tutorial which is in-depth, but as always with these things, it’s easy to miss stuff between the cracks. Grinberg is more thorough, though maybe a little harder.

The flask subreddit is alive and kicking as well.

1 Like

hmm. Okay, then thanks a lot!

Hi

I also got stuck with the same task and this worked for me.

>>> from app import db
>>> from models import Song, Playlist, Item, User
>>> db.create_all()

Do you think this instruction is enough?

1 Like

Then the instructions are missing that middle line bit, incidentally instead of from models import Song, Playlist, Item, User

you can type from models import * to save yourself some typing in the shell.

Yeah, the * is short for all, so save yourself some typing!

Definitely not enough instructions, lot of bugs in Flask Path.

@core9221442141 thanks for the tip to import from models. I have been spinning my wheels for hours trying to figure out where the code went wrong!

This is the first major bug I have found in the Flask path. Otherwise it has been pretty smooth sailing.