SlideShare uma empresa Scribd logo
1 de 31
Baixar para ler offline
SQLAlchemy SQLの錬金術
Plone Symposym Tokyo 2015
aodag
「Who Are You?」
Atsushi Odagiri
Use Python from 2001
Work at Be Proud, Inc.
What is SQLAlchemy?
Python Library for Data Accessing to RDBMS.
That has SQL Expression and OR Mapper.
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.
SQLAlchemy features
SQL Expression
Object-Relational Mapper
Unit 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 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
OR Mapper
mapper(User, users)
user = Session.query(User).filter(
User.first_name == u’Atsushi’).first()
user.first_name = u’aodag’
Session.flush()
Unit Of Work
There are no save method.
Session object manages Object states.
That calls DML depending on the object state.
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()
Getting Started
Install
Declare Models
Connect
Create Table
Query Model
Use Session
Install SQLAlchemy
pip install sqlalchemy
option:: Database Drivers
pip install psycopg2
pip 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 property
from sqlalchemy.ext.hybrid import (
hybrid_property,
)
@hybrid_property
def full_name(self):
return (self.first_name
+ “ “
+ self.last_name)
Connect
engine = create_engine(‘sqlite:///’)
connection url
postgresql://user:password@localhost/db
mysql+pymysql://user:
password@localhost/db
Create Table
Base.meatadata.create_all(bind=engine)
Query Model
from sqlalchemy.orm import (
scoped_session,
sessionmaker,
)
Session = scoped_session(sessionmaker())
Session.configure(bind=engine)
Query Model
aodag = Session.query(User).filter(
User.full_name == u’Atsushi Odagiri’
).one()
Session And Transaction
Session.remove()
Session.add(user)
Session.flush()
Session.commit()
With Web Application
Transaction Manager With zope.sqlalchemy
● repoze.tm2
● pyramid_tm
● Zope2 transaction
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()
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’)
Conclusion
SQLAlchemy 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

Mais conteúdo relacionado

Mais procurados

Introduction to database
Introduction to databaseIntroduction to database
Introduction to database
Kazi Uddin Oly
 

Mais procurados (20)

The Ring programming language version 1.10 book - Part 37 of 212
The Ring programming language version 1.10 book - Part 37 of 212The Ring programming language version 1.10 book - Part 37 of 212
The Ring programming language version 1.10 book - Part 37 of 212
 
Introduction to database
Introduction to databaseIntroduction to database
Introduction to database
 
Introduction to database
Introduction to databaseIntroduction to database
Introduction to database
 
Web Security - Hands-on
Web Security - Hands-onWeb Security - Hands-on
Web Security - Hands-on
 
JavaFX and Scala - Like Milk and Cookies
JavaFX and Scala - Like Milk and CookiesJavaFX and Scala - Like Milk and Cookies
JavaFX and Scala - Like Milk and Cookies
 
ERRest - The Next Steps
ERRest - The Next StepsERRest - The Next Steps
ERRest - The Next Steps
 
I regret nothing
I regret nothingI regret nothing
I regret nothing
 
The Ring programming language version 1.10 book - Part 47 of 212
The Ring programming language version 1.10 book - Part 47 of 212The Ring programming language version 1.10 book - Part 47 of 212
The Ring programming language version 1.10 book - Part 47 of 212
 
SenchaCon 2016: Theming the Modern Toolkit - Phil Guerrant
SenchaCon 2016: Theming the Modern Toolkit - Phil Guerrant   SenchaCon 2016: Theming the Modern Toolkit - Phil Guerrant
SenchaCon 2016: Theming the Modern Toolkit - Phil Guerrant
 
The Ring programming language version 1.2 book - Part 18 of 84
The Ring programming language version 1.2 book - Part 18 of 84The Ring programming language version 1.2 book - Part 18 of 84
The Ring programming language version 1.2 book - Part 18 of 84
 
Airline reservation project using JAVA in NetBeans IDE
Airline reservation project using JAVA in NetBeans IDEAirline reservation project using JAVA in NetBeans IDE
Airline reservation project using JAVA in NetBeans IDE
 
Brief introduction of Slick
Brief introduction of SlickBrief introduction of Slick
Brief introduction of Slick
 
FormsKit: reactive forms driven by state. UA Mobile 2017.
FormsKit: reactive forms driven by state. UA Mobile 2017.FormsKit: reactive forms driven by state. UA Mobile 2017.
FormsKit: reactive forms driven by state. UA Mobile 2017.
 
C# Advanced L03-XML+LINQ to XML
C# Advanced L03-XML+LINQ to XMLC# Advanced L03-XML+LINQ to XML
C# Advanced L03-XML+LINQ to XML
 
jQuery Rescue Adventure
jQuery Rescue AdventurejQuery Rescue Adventure
jQuery Rescue Adventure
 
The Ring programming language version 1.9 book - Part 36 of 210
The Ring programming language version 1.9 book - Part 36 of 210The Ring programming language version 1.9 book - Part 36 of 210
The Ring programming language version 1.9 book - Part 36 of 210
 
Rapid prototyping search applications with solr
Rapid prototyping search applications with solrRapid prototyping search applications with solr
Rapid prototyping search applications with solr
 
Web2py
Web2pyWeb2py
Web2py
 
Elixir and OTP Apps introduction
Elixir and OTP Apps introductionElixir and OTP Apps introduction
Elixir and OTP Apps introduction
 
Rails Concurrency Gotchas
Rails Concurrency GotchasRails Concurrency Gotchas
Rails Concurrency Gotchas
 

Destaque

Destaque (15)

PyCon 2010 SQLAlchemy tutorial
PyCon 2010 SQLAlchemy tutorialPyCon 2010 SQLAlchemy tutorial
PyCon 2010 SQLAlchemy tutorial
 
セールスエンジニアとして今後身につけていきたい技術
セールスエンジニアとして今後身につけていきたい技術セールスエンジニアとして今後身につけていきたい技術
セールスエンジニアとして今後身につけていきたい技術
 
自分のチームをどう作る?
自分のチームをどう作る?自分のチームをどう作る?
自分のチームをどう作る?
 
Building data flows with Celery and SQLAlchemy
Building data flows with Celery and SQLAlchemyBuilding data flows with Celery and SQLAlchemy
Building data flows with Celery and SQLAlchemy
 
Python3 移行への軌跡
Python3 移行への軌跡Python3 移行への軌跡
Python3 移行への軌跡
 
あなたのScalaを爆速にする7つの方法
あなたのScalaを爆速にする7つの方法あなたのScalaを爆速にする7つの方法
あなたのScalaを爆速にする7つの方法
 
Introduction to SQLAlchemy ORM
Introduction to SQLAlchemy ORMIntroduction to SQLAlchemy ORM
Introduction to SQLAlchemy ORM
 
あなたのScalaを爆速にする7つの方法(日本語版)
あなたのScalaを爆速にする7つの方法(日本語版)あなたのScalaを爆速にする7つの方法(日本語版)
あなたのScalaを爆速にする7つの方法(日本語版)
 
続Pythonによるwebスクレイピング入門
続Pythonによるwebスクレイピング入門続Pythonによるwebスクレイピング入門
続Pythonによるwebスクレイピング入門
 
はてなブックマーク in Scala
はてなブックマーク in Scalaはてなブックマーク in Scala
はてなブックマーク in Scala
 
はてなブックマークにおけるアクセス制御 - 半環構造に基づくモデル化
はてなブックマークにおけるアクセス制御 - 半環構造に基づくモデル化はてなブックマークにおけるアクセス制御 - 半環構造に基づくモデル化
はてなブックマークにおけるアクセス制御 - 半環構造に基づくモデル化
 
Kubernetesを触ってみた
Kubernetesを触ってみたKubernetesを触ってみた
Kubernetesを触ってみた
 
PythonによるWebスクレイピング入門
PythonによるWebスクレイピング入門PythonによるWebスクレイピング入門
PythonによるWebスクレイピング入門
 
パッケージングを支える技術 pyconjp2016
パッケージングを支える技術 pyconjp2016パッケージングを支える技術 pyconjp2016
パッケージングを支える技術 pyconjp2016
 
Kubernetesにまつわるエトセトラ(主に苦労話)
Kubernetesにまつわるエトセトラ(主に苦労話)Kubernetesにまつわるエトセトラ(主に苦労話)
Kubernetesにまつわるエトセトラ(主に苦労話)
 

Semelhante a Sqlalchemy sqlの錬金術

SQL Server 2005 CLR Integration
SQL Server 2005 CLR IntegrationSQL Server 2005 CLR Integration
SQL Server 2005 CLR Integration
webhostingguy
 
#SPSEMEA SharePoint & jQuery - What I wish I would have known a year ago..
#SPSEMEA SharePoint & jQuery - What I wish I would have known a year ago..#SPSEMEA SharePoint & jQuery - What I wish I would have known a year ago..
#SPSEMEA SharePoint & jQuery - What I wish I would have known a year ago..
Mark Rackley
 
Michael Bayer Introduction to SQLAlchemy @ Postgres Open
Michael Bayer Introduction to SQLAlchemy @ Postgres OpenMichael Bayer Introduction to SQLAlchemy @ Postgres Open
Michael Bayer Introduction to SQLAlchemy @ Postgres Open
PostgresOpen
 
Ruby on Rails Oracle adaptera izstrāde
Ruby on Rails Oracle adaptera izstrādeRuby on Rails Oracle adaptera izstrāde
Ruby on Rails Oracle adaptera izstrāde
Raimonds Simanovskis
 

Semelhante a Sqlalchemy sqlの錬金術 (20)

SQL Provider
SQL ProviderSQL Provider
SQL Provider
 
Alternatives of JPA/Hibernate
Alternatives of JPA/HibernateAlternatives of JPA/Hibernate
Alternatives of JPA/Hibernate
 
An introduction to SQLAlchemy
An introduction to SQLAlchemyAn introduction to SQLAlchemy
An introduction to SQLAlchemy
 
SADI in Perl - Protege Plugin Tutorial (fixed Aug 24, 2011)
SADI in Perl - Protege Plugin Tutorial (fixed Aug 24, 2011)SADI in Perl - Protege Plugin Tutorial (fixed Aug 24, 2011)
SADI in Perl - Protege Plugin Tutorial (fixed Aug 24, 2011)
 
SQL Server 2005 CLR Integration
SQL Server 2005 CLR IntegrationSQL Server 2005 CLR Integration
SQL Server 2005 CLR Integration
 
When to no sql and when to know sql javaone
When to no sql and when to know sql   javaoneWhen to no sql and when to know sql   javaone
When to no sql and when to know sql javaone
 
NoSQL Endgame DevoxxUA Conference 2020
NoSQL Endgame DevoxxUA Conference 2020NoSQL Endgame DevoxxUA Conference 2020
NoSQL Endgame DevoxxUA Conference 2020
 
Agile Data Science 2.0
Agile Data Science 2.0Agile Data Science 2.0
Agile Data Science 2.0
 
Using T-SQL
Using T-SQL Using T-SQL
Using T-SQL
 
Simon Elliston Ball – When to NoSQL and When to Know SQL - NoSQL matters Barc...
Simon Elliston Ball – When to NoSQL and When to Know SQL - NoSQL matters Barc...Simon Elliston Ball – When to NoSQL and When to Know SQL - NoSQL matters Barc...
Simon Elliston Ball – When to NoSQL and When to Know SQL - NoSQL matters Barc...
 
Naver_alternative_to_jpa
Naver_alternative_to_jpaNaver_alternative_to_jpa
Naver_alternative_to_jpa
 
#SPSEMEA SharePoint & jQuery - What I wish I would have known a year ago..
#SPSEMEA SharePoint & jQuery - What I wish I would have known a year ago..#SPSEMEA SharePoint & jQuery - What I wish I would have known a year ago..
#SPSEMEA SharePoint & jQuery - What I wish I would have known a year ago..
 
A "M"ind Bending Experience. Power Query for Power BI and Beyond.
A "M"ind Bending Experience. Power Query for Power BI and Beyond.A "M"ind Bending Experience. Power Query for Power BI and Beyond.
A "M"ind Bending Experience. Power Query for Power BI and Beyond.
 
Agile Data Science 2.0
Agile Data Science 2.0Agile Data Science 2.0
Agile Data Science 2.0
 
Michael Bayer Introduction to SQLAlchemy @ Postgres Open
Michael Bayer Introduction to SQLAlchemy @ Postgres OpenMichael Bayer Introduction to SQLAlchemy @ Postgres Open
Michael Bayer Introduction to SQLAlchemy @ Postgres Open
 
Scalar user defined function in sap hana
Scalar user defined function in sap hanaScalar user defined function in sap hana
Scalar user defined function in sap hana
 
Swift, functional programming, and the future of Objective-C
Swift, functional programming, and the future of Objective-CSwift, functional programming, and the future of Objective-C
Swift, functional programming, and the future of Objective-C
 
Ruby on Rails Oracle adaptera izstrāde
Ruby on Rails Oracle adaptera izstrādeRuby on Rails Oracle adaptera izstrāde
Ruby on Rails Oracle adaptera izstrāde
 
Agile Data Science 2.0 - Big Data Science Meetup
Agile Data Science 2.0 - Big Data Science MeetupAgile Data Science 2.0 - Big Data Science Meetup
Agile Data Science 2.0 - Big Data Science Meetup
 
Intro to PySpark: Python Data Analysis at scale in the Cloud
Intro to PySpark: Python Data Analysis at scale in the CloudIntro to PySpark: Python Data Analysis at scale in the Cloud
Intro to PySpark: Python Data Analysis at scale in the Cloud
 

Mais de Atsushi Odagiri

パッケージングの今
パッケージングの今パッケージングの今
パッケージングの今
Atsushi Odagiri
 
パッケージングの今と未来
パッケージングの今と未来パッケージングの今と未来
パッケージングの今と未来
Atsushi Odagiri
 
パッケージングの今と未来
パッケージングの今と未来パッケージングの今と未来
パッケージングの今と未来
Atsushi Odagiri
 
Pyconjp2012 memory-of-europython
Pyconjp2012 memory-of-europythonPyconjp2012 memory-of-europython
Pyconjp2012 memory-of-europython
Atsushi Odagiri
 
What makes pyramid unique
What makes pyramid uniqueWhat makes pyramid unique
What makes pyramid unique
Atsushi Odagiri
 
エキPy lt repoze.whoの紹介
エキPy lt repoze.whoの紹介エキPy lt repoze.whoの紹介
エキPy lt repoze.whoの紹介
Atsushi Odagiri
 
BPStudy#54 そろそろPython3
BPStudy#54 そろそろPython3BPStudy#54 そろそろPython3
BPStudy#54 そろそろPython3
Atsushi Odagiri
 

Mais de Atsushi Odagiri (20)

みんなのPython勉強会#77 パッケージングしよう
みんなのPython勉強会#77 パッケージングしようみんなのPython勉強会#77 パッケージングしよう
みんなのPython勉強会#77 パッケージングしよう
 
async/await の向こう側 PyCon Kyushu 2022
async/await の向こう側 PyCon Kyushu 2022async/await の向こう側 PyCon Kyushu 2022
async/await の向こう側 PyCon Kyushu 2022
 
パッケージングの呼び声 Python Charity Talks in Japan 2021.02
パッケージングの呼び声 Python Charity Talks in Japan 2021.02パッケージングの呼び声 Python Charity Talks in Japan 2021.02
パッケージングの呼び声 Python Charity Talks in Japan 2021.02
 
eggとはなんだったのか 栄光のsetuptools
eggとはなんだったのか 栄光のsetuptoolseggとはなんだったのか 栄光のsetuptools
eggとはなんだったのか 栄光のsetuptools
 
pyconjp 2019 LT 今日のsetuptools
pyconjp 2019 LT 今日のsetuptoolspyconjp 2019 LT 今日のsetuptools
pyconjp 2019 LT 今日のsetuptools
 
Pythonでの開発を効率的に進めるためのツール設定
Pythonでの開発を効率的に進めるためのツール設定Pythonでの開発を効率的に進めるためのツール設定
Pythonでの開発を効率的に進めるためのツール設定
 
Pythonとパッケージングと私
Pythonとパッケージングと私Pythonとパッケージングと私
Pythonとパッケージングと私
 
Clack meetup #1 lt
Clack meetup #1 ltClack meetup #1 lt
Clack meetup #1 lt
 
Pyramid入門
Pyramid入門Pyramid入門
Pyramid入門
 
パッケージングの今
パッケージングの今パッケージングの今
パッケージングの今
 
パッケージングの今と未来
パッケージングの今と未来パッケージングの今と未来
パッケージングの今と未来
 
パッケージングの今と未来
パッケージングの今と未来パッケージングの今と未来
パッケージングの今と未来
 
Bplt11 form alchemy
Bplt11 form alchemyBplt11 form alchemy
Bplt11 form alchemy
 
Python3でwebアプリ
Python3でwebアプリPython3でwebアプリ
Python3でwebアプリ
 
Pyconjp2012 memory-of-europython
Pyconjp2012 memory-of-europythonPyconjp2012 memory-of-europython
Pyconjp2012 memory-of-europython
 
What makes pyramid unique
What makes pyramid uniqueWhat makes pyramid unique
What makes pyramid unique
 
エキPy lt repoze.whoの紹介
エキPy lt repoze.whoの紹介エキPy lt repoze.whoの紹介
エキPy lt repoze.whoの紹介
 
World plonedaylt
World plonedayltWorld plonedaylt
World plonedaylt
 
Setup.pysetup.cfg
Setup.pysetup.cfgSetup.pysetup.cfg
Setup.pysetup.cfg
 
BPStudy#54 そろそろPython3
BPStudy#54 そろそろPython3BPStudy#54 そろそろPython3
BPStudy#54 そろそろPython3
 

Sqlalchemy sqlの錬金術