'attribute error (key) in sqlalchemy-flask application, cant connect to database
this is my first time asking a question on stackoverflow. Im in a data science bootcamp and I missed a class and I am going through the recording and trying to follow along with the instructor showing us how to reference a sqlite database in a flask app, but I cant get the example running. Im able to run flask apps that dont reference sqlite though. For example, when i try and run python code that begins with this:
import numpy as np
import sqlalchemy
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
from sqlalchemy import create_engine, func
from flask import Flask, jsonify
#################################################
# Database Setup
#################################################
engine = create_engine("sqlite:///titanic.sqlite")
# reflect an existing database into a new model
Base = automap_base()
# reflect the tables
Base.prepare(engine, reflect=True)
# Save reference to the table
Passenger = Base.classes.passenger
#################################################
# Flask Setup
#################################################
app = Flask(__name__)
im greeted with an error that says
Traceback (most recent call last):
File "C:\Users\frcon\Anaconda3\lib\site-packages\sqlalchemy\util\_collections.py", line 210, in __getattr__
return self._data[key]
KeyError: 'passenger'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "c:/Users/frcon/Desktop/pythonstuff/RU-JER-DATA-PT-01-2020/01-Lesson-Plans/10-Advanced-Data-Storage-and-Retrieval/3/Activities/10-Ins_Flask_with_ORM/Solved/app.py", line 22, in <module>
Passenger = Base.classes.passenger
File "C:\Users\frcon\Anaconda3\lib\site-packages\sqlalchemy\util\_collections.py", line 212, in __getattr__
raise AttributeError(key)
AttributeError: passenger
I guess it means that it cant find the "passenger" table but im sure it exists, I checked the database. In the recording of class, my professor was able to run this code without modifying anything. Any help is super appreciate. Thanks!
Solution 1:[1]
Is the passenger table spelled the same in titanic.sqlite file they way you are referencing it?
You can run the following in jupyter notebook with the same dependencies.
engine = create_engine("sqlite:///titanic.sqlite")
Base = automap_base()
Base.prepare(engine, reflect=True)
# This should return the table names
Base.classes.keys()
Solution 2:[2]
My issue was that i needed to import os :)
Solution 3:[3]
engine = create_engine("sqlite:///titanic.sqlite")
The issue is in above line: add full path like "c:/user/myname/desktop/myapp/titanic.sqlite" instead of just "titanic.sqlite"
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | AtxTom |
| Solution 2 | cone f |
| Solution 3 | FAIZ AHMED |
