Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Sqlalchemy sqlの錬金術

1,817 views

Published on

  • Be the first to comment

Sqlalchemy sqlの錬金術

  1. 1. SQLAlchemy SQLの錬金術 Plone Symposym Tokyo 2015 aodag
  2. 2. 「Who Are You?」 Atsushi Odagiri Use Python from 2001 Work at Be Proud, Inc.
  3. 3. What is SQLAlchemy? Python Library for Data Accessing to RDBMS. That has SQL Expression and OR Mapper.
  4. 4. Why I use SQLAlchemy I 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.
  5. 5. SQLAlchemy features SQL Expression Object-Relational Mapper Unit of Work
  6. 6. 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’)))
  7. 7. SQL Expression (Insert) users.insert().values( first_name=u”Atsushi”, last_name=u”Odagiri”, )
  8. 8. SQL Expression(Select) select([users]).where( users.c.first_name==u’Atsushi’, )
  9. 9. OR Mapper class 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
  10. 10. OR Mapper mapper(User, users) user = Session.query(User).filter( User.first_name == u’Atsushi’).first() user.first_name = u’aodag’ Session.flush()
  11. 11. Unit Of Work There are no save method. Session object manages Object states. That calls DML depending on the object state.
  12. 12. Unit Of Work user = User(u’Atsushi’, u’Odagiri’) Session.add(user) user.company = Company(u’BeProud’) Session.flush() user.first_name = u’aodag’ Session.flush()
  13. 13. Getting Started Install Declare Models Connect Create Table Query Model Use Session
  14. 14. Install SQLAlchemy pip install sqlalchemy option:: Database Drivers pip install psycopg2 pip install mysql-python ...
  15. 15. Declare Models (DataType) from sqlalchemy import ( Colum, Unicode, Integer, DateTime, ForeignKey, )
  16. 16. Declare Models (ORM) from sqlalchemy.orm import ( relationship, ) from sqlalchemy.ext.declarative import ( delcarative_base, )
  17. 17. Declare Models (class) Base = declarative_base() class User(Base): __tablename__ = ‘users’ ...
  18. 18. Declare Models (Property) id = Column(Integer, primary_key=True) first_name = Column(Unicode(255)) last_name = Column(Unicode(255))
  19. 19. hybrid property from sqlalchemy.ext.hybrid import ( hybrid_property, )
  20. 20. @hybrid_property def full_name(self): return (self.first_name + “ “ + self.last_name)
  21. 21. Connect engine = create_engine(‘sqlite:///’) connection url postgresql://user:password@localhost/db mysql+pymysql://user: password@localhost/db
  22. 22. Create Table Base.meatadata.create_all(bind=engine)
  23. 23. Query Model from sqlalchemy.orm import ( scoped_session, sessionmaker, ) Session = scoped_session(sessionmaker()) Session.configure(bind=engine)
  24. 24. Query Model aodag = Session.query(User).filter( User.full_name == u’Atsushi Odagiri’ ).one()
  25. 25. Session And Transaction Session.remove() Session.add(user) Session.flush() Session.commit()
  26. 26. With Web Application Transaction Manager With zope.sqlalchemy ● repoze.tm2 ● pyramid_tm ● Zope2 transaction
  27. 27. With Web Application Transaction WSGI Middleware @wsgify.middleware def transaction_middleware(app, req, session): try: return req.get_response(app) except: session.rollback() else: session.commit()
  28. 28. With asyncio/aiopg @async.coroutine def get(): with (yeild from engine) as con: res = yeild from con.execute( select([users]).where( users.c.first_name == u’Atsushi’)
  29. 29. Conclusion SQLAlchemy has many features. SQLAlchemy supports many kind of SQL Statements. That’s Great!
  30. 30. 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
  31. 31. That’s all

×