Reputation: 2706
Here is my code :
from flask import Flask
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from database_setup import Base, Restaurant, MenuItem
app = Flask(__name__)
engine = create_engine('sqlite:///restaurantmenu.db')
Base.metadata.bind = engine
DBSession = sessionmaker(bind=engine)
session = DBSession()
@app.route('/')
@app.route('/restaurants/<int:restaurant_id>/')
def restaurantMenu(restaurant_id):
restaurant = session.query(Restaurant).filter_by(id=restaurant_id).one()
items = session.query(MenuItem).filter_by(restaurant_id=restaurant.id)
output = ''
for i in items:
output += i.name
output += '</br>'
output += i.price
output += '</br>'
output += i.description
output += '</br>'
output += '</br>'
return output
if __name__ == '__main__':
app.debug = True
app.run(host='0.0.0.0', port=5000)
I run the file by entering the following URL :
localhost:5000/restaurants/2
And all I get is a blank page. I don't get any kind of error in my GitBash or browser or anywhere else.
I ran this simple code :
from flask import Flask
app = Flask(__name__)
@app.route('/')
@app.route('/hello')
def HelloWorld():
return "Hello World"
if __name__ == '__main__':
app.debug = True
app.run(host='0.0.0.0', port=5000)
And this runs perfectly. What wrong am I doing ?
EDIT : 1
Tried to debug the code and noticed that the code doesn't enter the for i in items:
loop.
@app.route('/')
@app.route('/hello')
def restaurantMenu():
restaurant = session.query(Restaurant).first()
items = session.query(MenuItem).filter_by(restaurant_id = restaurant.id)
output = ''
print restaurant.name
print restaurant.id
if not items :
print "No menu items!"
else:
print "There are menu items!"
for i in items:
print "In items loop!"
output += i.name
output += '<br>'
return output + "Hello"
Upvotes: 0
Views: 423
Reputation: 1503
Basically you need the all() function at your items
. You are querying properly but you are not fetching the results.
so your code will be like this
@app.route('/')
@app.route('/restaurants/<int:restaurant_id>/')
def restaurantMenu(restaurant_id):
restaurant = session.query(Restaurant).filter_by(id=restaurant_id).one()
items = session.query(MenuItem).filter_by(restaurant_id=restaurant.id).all()
output = ''
for i in items:
output += i.name
output += '</br>'
output += i.price
output += '</br>'
output += i.description
output += '</br>'
output += '</br>'
return output
if __name__ == '__main__':
app.debug = True
app.run(host='0.0.0.0', port=5000)
Now it will depend on the entries in your db, if you have any or else it will return an empty []
. So if you have the results, you can print and check or loop and render it to your templates.
This should fix your issue
Upvotes: 1