O'Reilly logo

Essential SQLAlchemy, 2nd Edition by Rick Copeland, Jason Myers

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 14. Cookbook

This chapter is different than previous ones in that each section focuses on a different aspect of using SQLAlchemy. The coverage here isn’t as detailed as in previous chapters; consider this a quick rundown of useful tools. At the end of each section, there’s information about where you can learn more if you’re interested. These sections are not meant to be full tutorials, but rather short recipes on how to accomplish a particular task. The first part of this chapter focuses on a few advanced usages of SQLAlchemy, the second part on using SQLAlchemy with web frameworks like Flask, and the final section on additional libraries that can be used with SQLAlchemy.

Hybrid Attributes

Hybrid attributes are those that exhibit one behavior when accessed as a class method, and another behavior when accessed on an instance. Another way to think of this is that the attribute will generate valid SQL when it is used in a SQLAlchemy statement, and when accessed on an instance the hybrid attribute will execute the Python code directly against the instance. I find it easiest to understand this when looking at code. We’re going to use our Cookie declarative class to illustrate this in Example 14-1.

Example 14-1. Our Cookie user data model
from datetime import datetime

from sqlalchemy import Column, Integer, Numeric, String, create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.ext.hybrid import hybrid_property, hybrid_method
from sqlalchemy.orm ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required