November 2015
Intermediate to advanced
208 pages
4h 22m
English
In the previous chapter, we did a lot of work with the session, and we avoided doing anything that could result in an exception. In this chapter, we will learn a bit more about how our objects and the SQLAlchemy session interact. We’ll conclude this chapter by purposely performing some actions incorrectly so that we can see the types of exceptions that occur and how we should respond to them. Let’s start by learning more about the session. First, we’ll set up an in-memory SQLite database using the tables from Chapter 6:
fromsqlalchemyimportcreate_enginefromsqlalchemy.ormimportsessionmakerengine=create_engine('sqlite:///:memory:')Session=sessionmaker(bind=engine)session=Session()fromdatetimeimportdatetimefromsqlalchemyimport(Table,Column,Integer,Numeric,String,DateTime,ForeignKey,Boolean)fromsqlalchemy.ext.declarativeimportdeclarative_basefromsqlalchemy.ormimportrelationship,backrefBase=declarative_base()classCookie(Base):__tablename__='cookies'cookie_id=Column(Integer,primary_key=True)cookie_name=Column(String(50),index=True)cookie_recipe_url=Column(String(255))cookie_sku=Column(String(55))quantity=Column(Integer())unit_cost=Column(Numeric(12,2))def__init__(self,name,recipe_url=None,sku=None,quantity=0,unit_cost=0.00):self.cookie_name=nameself.cookie_recipe_url=recipe_urlself.cookie_sku=skuself.quantity=quantityself.unit_cost=unit_cost ...
Read now
Unlock full access