diff options
Diffstat (limited to 'customer.py')
| -rw-r--r-- | customer.py | 52 |
1 files changed, 52 insertions, 0 deletions
diff --git a/customer.py b/customer.py new file mode 100644 index 0000000..e707346 --- /dev/null +++ b/customer.py | |||
| @@ -0,0 +1,52 @@ | |||
| 1 | import sqlalchemy | ||
| 2 | from sqlalchemy import * | ||
| 3 | from sqlalchemy.ext.declarative import declarative_base | ||
| 4 | from sqlalchemy.orm.exc import NoResultFound, MultipleResultsFound | ||
| 5 | from webob import Response | ||
| 6 | from webob.exc import HTTPFound | ||
| 7 | import db, product | ||
| 8 | |||
| 9 | Base = declarative_base() | ||
| 10 | class Customer(Base): | ||
| 11 | __tablename__ = 'customers' | ||
| 12 | |||
| 13 | id = Column(Integer, primary_key=True) | ||
| 14 | email = Column(String) | ||
| 15 | name = Column(String) | ||
| 16 | |||
| 17 | def __init__(self, name, email ): | ||
| 18 | self.name = name | ||
| 19 | self.email = email | ||
| 20 | session = db.Session() | ||
| 21 | session.add( self ) | ||
| 22 | session.commit() | ||
| 23 | |||
| 24 | def __repr__(self): | ||
| 25 | return "<User('%s, %s')>" % (self.name, self.email) | ||
| 26 | |||
| 27 | def list(request): | ||
| 28 | session = db.Session() | ||
| 29 | customers = {} | ||
| 30 | products = {} | ||
| 31 | for cust in session.query(Customer).order_by(Customer.id): | ||
| 32 | customers[ cust.id ] = { 'name': cust.name, 'email': cust.email } | ||
| 33 | for prod in session.query(product.Product).order_by(product.Product.id): | ||
| 34 | products[ prod.id ] = { 'name': prod.name, 'type': prod.type, 'price': prod.price } | ||
| 35 | session.close() | ||
| 36 | return { 'customers': customers, 'products': products } | ||
| 37 | |||
| 38 | def info(request): | ||
| 39 | session = db.Session() | ||
| 40 | try: | ||
| 41 | customer = session.query(Customer).filter(Customer.name == request.matchdict['customer'] ).one() | ||
| 42 | resp = "User: id=%s name=%s email=%s<br>" % ( customer.id, customer.name, customer.email ) | ||
| 43 | except MultipleResultsFound, e: | ||
| 44 | resp = "Multiple users found with name %s." % request.matchdict['customer'] | ||
| 45 | except NoResultFound, e: | ||
| 46 | resp = "User %s unknown." % request.matchdict['customer'] | ||
| 47 | return Response( resp ) | ||
| 48 | |||
| 49 | def new(request): | ||
| 50 | newUser = Customer( request.params['name'], request.params['email'] ) | ||
| 51 | destination = "/customers/%s" % newUser.name | ||
| 52 | return HTTPFound( location = destination ) | ||
