sqlalchemy sqlの錬金術
TRANSCRIPT
SQLAlchemy SQLの錬金術Plone Symposym Tokyo 2015
aodag
「Who Are You?」Atsushi OdagiriUse Python from 2001Work at Be Proud, Inc.
What is SQLAlchemy?
Python Library for Data Accessing to RDBMS.
That has SQL Expression and OR Mapper.
Why I use SQLAlchemyI Don’t Know Other OR Mapper with Python.
I Love SQL And Python!SQLAlchemy has SQL Expression That makes SQL Python Object.SQLAlchemy doesn’t keep me away from SQL.
SQLAlchemy featuresSQL ExpressionObject-Relational MapperUnit of Work
SQL Expression(schema)users = Table(“users”, metadata,Column(‘id’, Integer, primary_key=True),Column(‘first_name’, Unicode(255)),Column(‘last_name’, Unicode(255)),Column(‘company_id’, Integer, ForeignKey(‘company.id’)))
SQL Expression (Insert)users.insert().values( first_name=u”Atsushi”, last_name=u”Odagiri”,)
SQL Expression(Select)select([users]).where( users.c.first_name==u’Atsushi’,)
OR Mapperclass User(object): def __init__(self, first_name, last_name): self.first_name = first_name self.last_name = last_name @property def full_name(self): return self.first_name + self.last_name
OR Mappermapper(User, users)
user = Session.query(User).filter( User.first_name == u’Atsushi’).first()user.first_name = u’aodag’Session.flush()
Unit Of WorkThere are no save method.Session object manages Object states.That calls DML depending on the object state.
Unit Of Workuser = User(u’Atsushi’, u’Odagiri’)Session.add(user)user.company = Company(u’BeProud’)Session.flush()user.first_name = u’aodag’Session.flush()
Getting StartedInstallDeclare ModelsConnectCreate TableQuery ModelUse Session
Install SQLAlchemypip install sqlalchemy
option:: Database Driverspip install psycopg2pip install mysql-python...
Declare Models (DataType)from sqlalchemy import ( Colum, Unicode, Integer, DateTime, ForeignKey,)
Declare Models (ORM)from sqlalchemy.orm import ( relationship,)from sqlalchemy.ext.declarative import ( delcarative_base,)
Declare Models (class)Base = declarative_base()
class User(Base): __tablename__ = ‘users’ ...
Declare Models (Property) id = Column(Integer, primary_key=True) first_name = Column(Unicode(255)) last_name = Column(Unicode(255))
hybrid propertyfrom sqlalchemy.ext.hybrid import ( hybrid_property,)
@hybrid_property def full_name(self): return (self.first_name + “ “ + self.last_name)
Connectengine = create_engine(‘sqlite:///’)
connection urlpostgresql://user:password@localhost/dbmysql+pymysql://user:password@localhost/db
Create TableBase.meatadata.create_all(bind=engine)
Query Modelfrom sqlalchemy.orm import ( scoped_session, sessionmaker,)Session = scoped_session(sessionmaker())Session.configure(bind=engine)
Query Modelaodag = Session.query(User).filter( User.full_name == u’Atsushi Odagiri’).one()
Session And TransactionSession.remove()Session.add(user)Session.flush()Session.commit()
With Web ApplicationTransaction Manager With zope.sqlalchemy● repoze.tm2● pyramid_tm● Zope2 transaction
With Web ApplicationTransaction WSGI [email protected] transaction_middleware(app, req, session): try: return req.get_response(app) except: session.rollback() else: session.commit()
With asyncio/[email protected] get(): with (yeild from engine) as con: res = yeild from con.execute( select([users]).where( users.c.first_name == u’Atsushi’)
ConclusionSQLAlchemy has many features.SQLAlchemy supports many kind of SQL Statements.
That’s Great!
Bib.● http://www.sqlalchemy.org/● http://aiopg.readthedocs.org/● http://repozetm2.readthedocs.org/● https://pypi.python.org/pypi/zope.
sqlalchemy● PEP 0249 -- Python Database API
Specification v2.0
That’s all