new to web developing. I have three files. database_setup.py with my table classes. restaurant.py used to populate tables and script.py for flask app
database_setup.py
import os
import sys
from sqlalchemy import Column, ForeignKey, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy import create_engine
Base = declarative_base()
class Restaurant(Base):
__tablename__ = 'restaurant'
id = Column(Integer, primary_key=True)
name = Column(String(250), nullable=False)
engine = create_engine('sqlite:///restaurantmenu.db')
Base.metadata.create_all(engine)
restaurant.py
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from database_setup import Restaurant, Base, MenuItem
engine = create_engine('sqlite:///restaurantmenu.db')
Base.metadata.bind = engine
DBSession = sessionmaker(bind=engine)
session = DBSession()
restaurant = Restaurant(name= "Kasra")
session.add(restaurant)
session.commit()
script.py
from flask import Flask
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker,scoped_session
from database_setup import Base, Restaurant
app = Flask(__name__)
engine = create_engine('sqlite:///restaurantmenu.db')
Base.metadata.bind = engine
DBSession = scoped_session(sessionmaker(bind=engine))
session = DBSession()
@app.route('/')
@app.route('/hello')
def HelloWorld():
restaurant = session.query(Restaurant).first()
return restaurant.name
if __name__ == "__main__":
app.run(debug=True)
What I want to do is import the database that was created in restarant.py to script.py. When I run the app it creates a new and empty database because I'm using "engine = "create_engine()" in script.py and I need to use it in order to bind with engine and use session.
The error I get when running app "AttributeError: 'NoneType' object has no attribute 'name'"
engine = create_engine(...)
call in your code. In bothrestaurant.py
andscript.py
, the only interaction that you have with the database is through the session, so construct yourscoped_session
instance indatabase_setup.py
and import the session into bothrestaurant.py
andscript.py
. – SuperShoot