import sqlalchemy from sqlalchemy import * from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm.exc import NoResultFound, MultipleResultsFound from webob import Response from webob.exc import HTTPFound import db, customer Base = declarative_base() class Product(Base): __tablename__ = 'products' id = Column(Integer, primary_key=True) name = Column(String) type = Column(String) price = Column(Integer) def __init__(self, name, type, price ): self.name = name self.type = type self.price = price session = db.Session() try: session.add( self ) session.commit() except sqlalchemy.exc.IntegrityError, e: session.rollback() def __repr__(self): return "" % (self.name, self.type, self.price) def list(request): session = db.Session() customers = {} products = {} for cust in session.query(customer.Customer).order_by(customer.Customer.id): customers[ cust.id ] = { 'name': cust.name, 'email': cust.email } for product in session.query(Product).order_by(Product.id): products[ product.id ] = { 'name': product.name, 'type': product.type, 'price': product.price } session.close() return { 'customers': customers, 'products': products } def info(request): session = db.Session() try: product = session.query(Product).filter(Product.name == request.matchdict['product'] ).one() resp = "User: id=%s name=%s type=%s price=%d
" % ( product.id, product.name, product.type, product.price ) except MultipleResultsFound, e: resp = "Multiple products found with name %s." % request.matchdict['product'] except NoResultFound, e: resp = "Product %s unknown." % request.matchdict['product'] return Response( resp ) def new(request): newProduct = Product( request.params['name'], request.params['type'], request.params['price'] ) destination = "/product/%s" % newProduct.name return HTTPFound( location = destination )