Runner Bean
Runner Bean

Reputation: 5195

python flask sqlalchemy - working with sqlite database from python terminal

I have a python script app.py using Flask and SQLAlchemy to make a web application.

I have a table in the app.py script

class NutritionConsumed(db.Model):
    __tablename__ = 'nutritionconsumed'
    id = db.Column(db.Integer, primary_key=True)
    date = db.Column(db.DateTime, nullable=False )
    item = db.Column(db.String(200), nullable=False)

in the same folder I have my sqlite database 'test.db'. Running in browser everything works fine and I can read and display data from my tables.

However, how do I access this database in the Python shell terminal?

When starting python in the same directory as my web app is located, if I run

>>> nutritionconsumed.query.all()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'nutritionconsumed' is not defined

but in my test.db I do have a nutritionconsumed table.

Upvotes: 0

Views: 1266

Answers (2)

alexdefelipe
alexdefelipe

Reputation: 197

The class representation of a table, in Flask, is called Model. User's model needs to be imported in order to be used, as every other class in Python:

from app import NutritionConsumed
NutritionConsumed.query.all()

Upvotes: 0

stasiekz
stasiekz

Reputation: 1863

nutritionconsumed is name of the table and such variable does not exist by default. If you want to query this model, you have to import its class and use the class name instead.

NutritionConsumed.query.all()

Upvotes: 3

Related Questions