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, product Base = declarative_base() class Customer(Base): __tablename__ = 'customers' id = Column(Integer, primary_key=True) email = Column(String) name = Column(String) def __init__(self, name, email ): self.name = name self.email = email session = db.Session() session.add( self ) session.commit() def __repr__(self): return "" % (self.name, self.email) def list(request): session = db.Session() customers = {} products = {} for cust in session.query(Customer).order_by(Customer.id): customers[ cust.id ] = { 'name': cust.name, 'email': cust.email } for prod in session.query(product.Product).order_by(product.Product.id): products[ prod.id ] = { 'name': prod.name, 'type': prod.type, 'price': prod.price } session.close() return { 'customers': customers, 'products': products } def info(request): session = db.Session() try: customer = session.query(Customer).filter(Customer.name == request.matchdict['customer'] ).one() resp = "User: id=%s name=%s email=%s
" % ( customer.id, customer.name, customer.email ) except MultipleResultsFound, e: resp = "Multiple users found with name %s." % request.matchdict['customer'] except NoResultFound, e: resp = "User %s unknown." % request.matchdict['customer'] return Response( resp ) def new(request): newUser = Customer( request.params['name'], request.params['email'] ) destination = "/customers/%s" % newUser.name return HTTPFound( location = destination )