Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

AttributeError from /Lesson-3/20_JSON-Solution/ #64

Open
Shehab-Muhammad opened this issue Jul 4, 2016 · 4 comments
Open

AttributeError from /Lesson-3/20_JSON-Solution/ #64

Shehab-Muhammad opened this issue Jul 4, 2016 · 4 comments

Comments

@Shehab-Muhammad
Copy link

Shehab-Muhammad commented Jul 4, 2016

I got this error

Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/flask/app.py", line 1836, in call
return self.wsgi_app(environ, start_response)
File "/usr/lib/python2.7/dist-packages/flask/app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/usr/lib/python2.7/dist-packages/flask/app.py", line 1403, in handle_exception
reraise(exc_type, exc_value, tb)
File "/usr/lib/python2.7/dist-packages/flask/app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "/usr/lib/python2.7/dist-packages/flask/app.py", line 1477, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/usr/lib/python2.7/dist-packages/flask/app.py", line 1381, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/usr/lib/python2.7/dist-packages/flask/app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
File "/usr/lib/python2.7/dist-packages/flask/app.py", line 1461, in dispatch_request
return self.view_functionsrule.endpoint
File "/vagrant/web_server/webbyflask.py", line 18, in restaurantMenuJSON
return item.serialize
AttributeError: 'MenuItem' object has no attribute 'serialize'

this my webbyflask.py

from flask import Flask, render_template, request, url_for, redirect, flash, jsonify
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from database_setup import Base, Restaurant, MenuItem
from flask.templating import render_template
app = Flask(__name__)


engine = create_engine('sqlite:///restaurantmenu.db')
Base.metadata.bind = engine

DBSession = sessionmaker(bind=engine)
session = DBSession()

@app.route('/restaurants/<int:restaurant_id>/menu/<int:menu_id>/JSON')
def restaurantMenuJSON(restaurant_id, menu_id):
    item = session.query(MenuItem).filter_by(id = menu_id).one()
    return item.serialize

and this is my database_setup.py

import sys
import os
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'
    name = Column(String(80), nullable = False)
    id = Column(Integer, primary_key = True)

class MenuItem(Base):
    __tablename__ = 'menu_item'

    name = Column(String(80), nullable = False)
    id = Column(Integer, primary_key = True)
    course = Column(String(250))
    description = Column(String(250))
    price = Column(String(8))
    restaurant_id = Column(Integer, ForeignKey('restaurant.id'))
    restaurant = relationship(Restaurant)

    @property
    def serialize(self):
        return {
            'name': self.name,
            'description': self.description,
            'id': self.id,
            'price': self.price,
            'course': self.course,
        }
@hpeddula
Copy link

Add the serialize method within the class declaration of the menu item class

@tomdecort
Copy link

tomdecort commented May 12, 2020

Hi,

I get the same error after I join tables. So how do you join tables and return the result in JSON?

`class JobContexts(db.Model):
tablename = 'job_contexts'
table_args = {'schema':'config'}
job_context_id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String)
execution_order = db.Column(db.Integer)

def __init__(self, job_context_id, name, execution_order):
    self.job_context_id = job_context_id
    self.name = name
    self.execution_order = execution_order

@property
def json(self):
    return to_json(self, self.__class__)

@property
def serialize(self):
    """Return object data in easily serializable format"""
    return {
        'job_context_id'  : self.job_context_id,
        'name'            : self.name,
        'execution_order' : self.execution_order
    }

class Jobs(db.Model):
tablename = 'jobs'
table_args = {'schema':'config'}
job_id = db.Column(db.Integer, primary_key=True)
job_name = db.Column(db.String, nullable=False)
job_context_id = db.Column(db.Integer, db.ForeignKey('JobContexts.job_context_id'))
execution_order = db.Column(db.Integer)
active = db.Column(db.Boolean)
depending_of_jobs = db.Column(db.Integer)

def __init__(self, job_id, job_name, job_context_id, execution_order, active, depending_of_jobs):
    self.job_id = job_id
    self.job_name = job_name
    self.job_context_id = job_context_id
    self.execution_order = execution_order
    self.active = active
    self.depending_of_jobs = depending_of_jobs

@property
def json(self):
    return to_json(self, self.__class__)

@property
def serialize(self):
   """Return object data in easily serializable format"""
   return {
       'job_id'            : self.job_id,
       'job_name'          : self.job_name,
       'job_context_id'    : self.job_context_id,
       'execution_order'   : self.execution_order,
       'depending_of_jobs' : self.depending_of_jobs
   }`

and

def getAllJobs(): #return jsonify(json_list = [i.serialize for i in jobs.query.all()]) ##> works fine! all_jobs = Jobs.query.join(JobContexts, Jobs.job_context_id == JobContexts.job_context_id).add_columns(JobContexts.name).all() return jsonify([i.serialize for i in all_jobs])

Anyone knows about good documentation about flask_sqlalchemy providing more info on how to join tables etc.?

Cheers,
Tom

@VarunAdithya
Copy link

return jsonify(Menu_List =[i.serialize for i in Menu_Item])

@ppingpping
Copy link

I got this error

Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/flask/app.py", line 1836, in call
return self.wsgi_app(environ, start_response)
File "/usr/lib/python2.7/dist-packages/flask/app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/usr/lib/python2.7/dist-packages/flask/app.py", line 1403, in handle_exception
reraise(exc_type, exc_value, tb)
File "/usr/lib/python2.7/dist-packages/flask/app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "/usr/lib/python2.7/dist-packages/flask/app.py", line 1477, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/usr/lib/python2.7/dist-packages/flask/app.py", line 1381, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/usr/lib/python2.7/dist-packages/flask/app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
File "/usr/lib/python2.7/dist-packages/flask/app.py", line 1461, in dispatch_request
return self.view_functionsrule.endpoint
File "/vagrant/web_server/webbyflask.py", line 18, in restaurantMenuJSON
return item.serialize
AttributeError: 'MenuItem' object has no attribute 'serialize'

this my webbyflask.py

from flask import Flask, render_template, request, url_for, redirect, flash, jsonify
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from database_setup import Base, Restaurant, MenuItem
from flask.templating import render_template
app = Flask(__name__)


engine = create_engine('sqlite:///restaurantmenu.db')
Base.metadata.bind = engine

DBSession = sessionmaker(bind=engine)
session = DBSession()

@app.route('/restaurants/<int:restaurant_id>/menu/<int:menu_id>/JSON')
def restaurantMenuJSON(restaurant_id, menu_id):
    item = session.query(MenuItem).filter_by(id = menu_id).one()
    return item.serialize

and this is my database_setup.py

import sys
import os
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'
    name = Column(String(80), nullable = False)
    id = Column(Integer, primary_key = True)

class MenuItem(Base):
    __tablename__ = 'menu_item'

    name = Column(String(80), nullable = False)
    id = Column(Integer, primary_key = True)
    course = Column(String(250))
    description = Column(String(250))
    price = Column(String(8))
    restaurant_id = Column(Integer, ForeignKey('restaurant.id'))
    restaurant = relationship(Restaurant)

    @property
    def serialize(self):
        return {
            'name': self.name,
            'description': self.description,
            'id': self.id,
            'price': self.price,
            'course': self.course,
        }

Hvuhionpm

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants