oauth2client.contrib.sqlalchemy module

OAuth 2.0 utilities for SQLAlchemy.

Utilities for using OAuth 2.0 in conjunction with a SQLAlchemy.

Configuration

In order to use this storage, you’ll need to create table with oauth2client.contrib.sqlalchemy.CredentialsType column. It’s recommended to either put this column on some sort of user info table or put the column in a table with a belongs-to relationship to a user info table.

Here’s an example of a simple table with a CredentialsType column that’s related to a user table by the user_id key.

from sqlalchemy import Column, ForeignKey, Integer
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship

from oauth2client.contrib.sqlalchemy import CredentialsType


Base = declarative_base()


class Credentials(Base):
    __tablename__ = 'credentials'

    user_id = Column(Integer, ForeignKey('user.id'))
    credentials = Column(CredentialsType)


class User(Base):
    id = Column(Integer, primary_key=True)
    # bunch of other columns
    credentials = relationship('Credentials')

Usage

With tables ready, you are now able to store credentials in database. We will reuse tables defined above.

from sqlalchemy.orm import Session

from oauth2client.client import OAuth2Credentials
from oauth2client.contrib.sql_alchemy import Storage

session = Session()
user = session.query(User).first()
storage = Storage(
    session=session,
    model_class=Credentials,
    # This is the key column used to identify
    # the row that stores the credentials.
    key_name='user_id',
    key_value=user.id,
    property_name='credentials',
)

# Store
credentials = OAuth2Credentials(...)
storage.put(credentials)

# Retrieve
credentials = storage.get()

# Delete
storage.delete()
class oauth2client.contrib.sqlalchemy.CredentialsType(protocol=2, pickler=None, comparator=None)[source]

Bases: sqlalchemy.sql.sqltypes.PickleType

Type representing credentials.

Alias for sqlalchemy.types.PickleType.

class oauth2client.contrib.sqlalchemy.Storage(session, model_class, key_name, key_value, property_name)[source]

Bases: oauth2client.client.Storage

Store and retrieve a single credential to and from SQLAlchemy. This helper presumes the Credentials have been stored as a Credentials column on a db model class.

locked_delete()[source]

Delete credentials from the SQLAlchemy datastore.

locked_get()[source]

Retrieve stored credential.

Returns:A oauth2client.Credentials instance or None.
locked_put(credentials)[source]

Write a credentials to the SQLAlchemy datastore.

Parameters:credentialsoauth2client.Credentials