sqlalchemy sqlの錬金術

31
SQLAlchemy SQLの錬金術 Plone Symposym Tokyo 2015 aodag

Upload: atsushi-odagiri

Post on 29-Jul-2015

550 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Sqlalchemy  sqlの錬金術

SQLAlchemy SQLの錬金術Plone Symposym Tokyo 2015

aodag

Page 2: Sqlalchemy  sqlの錬金術

「Who Are You?」Atsushi OdagiriUse Python from 2001Work at Be Proud, Inc.

Page 3: Sqlalchemy  sqlの錬金術

What is SQLAlchemy?

Python Library for Data Accessing to RDBMS.

That has SQL Expression and OR Mapper.

Page 4: Sqlalchemy  sqlの錬金術

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.

Page 5: Sqlalchemy  sqlの錬金術

SQLAlchemy featuresSQL ExpressionObject-Relational MapperUnit of Work

Page 6: Sqlalchemy  sqlの錬金術

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’)))

Page 7: Sqlalchemy  sqlの錬金術

SQL Expression (Insert)users.insert().values( first_name=u”Atsushi”, last_name=u”Odagiri”,)

Page 8: Sqlalchemy  sqlの錬金術

SQL Expression(Select)select([users]).where( users.c.first_name==u’Atsushi’,)

Page 9: Sqlalchemy  sqlの錬金術

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

Page 10: Sqlalchemy  sqlの錬金術

OR Mappermapper(User, users)

user = Session.query(User).filter( User.first_name == u’Atsushi’).first()user.first_name = u’aodag’Session.flush()

Page 11: Sqlalchemy  sqlの錬金術

Unit Of WorkThere are no save method.Session object manages Object states.That calls DML depending on the object state.

Page 12: Sqlalchemy  sqlの錬金術

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()

Page 13: Sqlalchemy  sqlの錬金術

Getting StartedInstallDeclare ModelsConnectCreate TableQuery ModelUse Session

Page 14: Sqlalchemy  sqlの錬金術

Install SQLAlchemypip install sqlalchemy

option:: Database Driverspip install psycopg2pip install mysql-python...

Page 15: Sqlalchemy  sqlの錬金術

Declare Models (DataType)from sqlalchemy import ( Colum, Unicode, Integer, DateTime, ForeignKey,)

Page 16: Sqlalchemy  sqlの錬金術

Declare Models (ORM)from sqlalchemy.orm import ( relationship,)from sqlalchemy.ext.declarative import ( delcarative_base,)

Page 17: Sqlalchemy  sqlの錬金術

Declare Models (class)Base = declarative_base()

class User(Base): __tablename__ = ‘users’ ...

Page 18: Sqlalchemy  sqlの錬金術

Declare Models (Property) id = Column(Integer, primary_key=True) first_name = Column(Unicode(255)) last_name = Column(Unicode(255))

Page 19: Sqlalchemy  sqlの錬金術

hybrid propertyfrom sqlalchemy.ext.hybrid import ( hybrid_property,)

Page 20: Sqlalchemy  sqlの錬金術

@hybrid_property def full_name(self): return (self.first_name + “ “ + self.last_name)

Page 21: Sqlalchemy  sqlの錬金術

Connectengine = create_engine(‘sqlite:///’)

connection urlpostgresql://user:password@localhost/dbmysql+pymysql://user:password@localhost/db

Page 22: Sqlalchemy  sqlの錬金術

Create TableBase.meatadata.create_all(bind=engine)

Page 23: Sqlalchemy  sqlの錬金術

Query Modelfrom sqlalchemy.orm import ( scoped_session, sessionmaker,)Session = scoped_session(sessionmaker())Session.configure(bind=engine)

Page 24: Sqlalchemy  sqlの錬金術

Query Modelaodag = Session.query(User).filter( User.full_name == u’Atsushi Odagiri’).one()

Page 25: Sqlalchemy  sqlの錬金術

Session And TransactionSession.remove()Session.add(user)Session.flush()Session.commit()

Page 26: Sqlalchemy  sqlの錬金術

With Web ApplicationTransaction Manager With zope.sqlalchemy● repoze.tm2● pyramid_tm● Zope2 transaction

Page 27: Sqlalchemy  sqlの錬金術

With Web ApplicationTransaction WSGI [email protected] transaction_middleware(app, req, session): try: return req.get_response(app) except: session.rollback() else: session.commit()

Page 28: Sqlalchemy  sqlの錬金術

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’)

Page 29: Sqlalchemy  sqlの錬金術

ConclusionSQLAlchemy has many features.SQLAlchemy supports many kind of SQL Statements.

That’s Great!

Page 31: Sqlalchemy  sqlの錬金術

That’s all