SlideShare a Scribd company logo
1 of 25
Download to read offline
DAL!
Database Abstraction Layer!
Utilizando as classes de acesso a dados
do WEB2PY em outros projetos Python.!
ORM!
ORM!X!
“DAL	
  é	
  uma	
  API	
  que	
  mapeia	
  objetos	
  Python	
  em	
  objetos	
  de	
  
banco	
  de	
  dados	
  como	
  queries,	
  tabelas,	
  e	
  registros.	
  A	
  DAL	
  
gera	
  códigos	
  SQL	
  dinâmicamente	
  em	
  tempo	
  real	
  uClizando	
  
sempre	
  o	
  dialeto	
  SQL	
  referente	
  ao	
  banco	
  de	
  dados	
  em	
  uso”	
  
-­‐ Massimo	
  Di	
  Pierro	
  -­‐	
  web2py.com/book	
  
Request	
  
Conexão,	
  modelagem	
  
DAL	
  
(Model)	
  
DATABASE	
  –	
  SQL/GQL	
  
http://twit2py.com/timeline/rochacbruno	
from gluon.sql import DAL,Field, Table	
db = DAL(‘postgres://username:password@host/db’)	
utline = db.define_table(‘usertimeline’,	
	 	Field(‘user’),	
	 	Field(‘tweet’),	
	 	Field(‘timestamp’,’datetime’),	
	 	migrate=True)	
SELECT user, tweet, timestamp 	
FROM usertimeline	
WHERE user = ‘rochacbruno’	
ORDER BY timestamp desc	
DAL	
  queries	
  
(Controller)	
  
def timeline():	
user = request.args[0]	
query = utline.user==user	
order = utline.timestamp	
rows = db(query).select(orderby=~order)	
return dict(timeline=rows) 	
Globals()	
  
Output	
  
Response	
  
(view)	
  
{‘timeline’:rows}	
for tweet in timeline:	
DO SOMETHING
• SQLite	
  
• PostgreSQL	
  
• MySQL	
  
• Oracle	
  
• MicrosoZ	
  SQL	
  Server	
  
• FireBird	
  
• DB2	
  
• Informix	
  
• Ingres.	
  
• Google	
  BigTable	
  
• Google	
  App	
  Engine	
  (GAE)	
  
• JDBC	
  +	
  executesql	
  
from	
  gluon.sql	
  import	
  DAL,	
  Field,	
  Table	
  
• Load	
  Balance	
  
• Replicação	
  de	
  dados	
  
• Conexões	
  simultâneas	
  a	
  diversos	
  bancos	
  de	
  dados	
  
• ConnecCon	
  Pooling	
  
• Migrações	
  AutomáCcas	
  
• Parsing	
  (Json,	
  CSV,	
  list,	
  dict)	
  
• Import	
  e	
  Export	
  -­‐	
  CSV	
  
• Constraints	
  
• TransacCons	
  
• CRUD	
  (	
  Queries,	
  Sets,	
  Joins,	
  Like,	
  Belongs....)	
  
• Computed	
  Fields	
  
• Virtual	
  Fields	
  
• Traversing	
  
• More....	
  
db	
  =	
  DAL(['mysql://host1','mysql://host2','mysql://host3'])	
  
db	
  =	
  DAL('sqlite://storage.db’,	
  check_reserved=['postgres',	
  'mssql’,’commom’,’all’])	
  
Replicação	
  /	
  FailOver	
  
Palavras	
  reservadas	
  
db	
  =	
  DAL('mysql://host1’,pool_size=10)	
  
Connec6on	
  Pooling	
  
>>>	
  print	
  db.executesql('SELECT	
  *	
  FROM	
  person;')	
  
[(1,	
  u’José'),	
  (2,	
  u’Mickael')]	
  
Last_sql	
  
>>>	
  rows	
  =	
  db().select(db.person.ALL)	
  
>>>	
  print	
  db._lastsql	
  
SELECT	
  person.id,	
  person.name	
  FROM	
  person;	
  
Raw_sql	
  
Distributed	
  Transac6on	
  
db_a	
  =	
  DAL('postgres://...')	
  
db_b	
  =	
  DAL('postgres://...')	
  
DAL.distributed_transacCon_commit(db_a,	
  db_b)	
  
db.commit()	
  
db.rollback()	
  
Transac6ons	
  
DAL.distributed_transacCon_rollback(db_a,	
  db_b)	
  
Exportar	
  o	
  banco	
  de	
  dados	
  para	
  CSV	
  
>>>	
  db.export_to_csv_file(open('somefile.csv',	
  'wb'))	
  
Importar	
  o	
  banco	
  de	
  dados	
  de	
  um	
  CSV	
  
>>>	
  db.import_from_csv_file(open('somefile.csv',	
  'rb'))	
  
Somefile.CSV	
  
TABLE	
  person	
  
person.id,person.name,person.language	
  
1,Claudia,Python	
  
2,Bruno,Python	
  
TABLE	
  dog	
  
dog.id,dog.name,dog.owner,dog.age,dog.realage	
  
1,chucrute,2,10,70.0	
  
2,Joy,1,2,14.0	
  
3,Pimenta,1,1,7.0	
  
4,Sultao,2,8,56.0	
  
END	
  
Retorno	
  do	
  db	
  como	
  XML	
  ou	
  JSON	
  
>>>	
  rows	
  =	
  db(db.person.id	
  >	
  0).select()	
  
>>>	
  print	
  rows.xml()	
  #	
  could	
  be	
  rows.json()	
  
<table>	
  
	
  	
  <thead>	
  
	
  	
  	
  	
  <tr>	
  
	
  	
  	
  	
  	
  	
  <th>person.id</th>	
  
	
  	
  	
  	
  	
  	
  <th>person.name</th>	
  
</tr>	
  
	
  	
  </thead>	
  
	
  	
  <tbody>	
  
	
  	
  	
  	
  <tr	
  class="even">	
  
	
  	
  	
  	
  	
  	
  <td>1</td>	
  
	
  	
  	
  	
  	
  	
  <td>Alex</td>	
  
	
  	
  	
  	
  	
  	
  <td>1</td>	
  
	
  	
  	
  	
  	
  	
  <td>Skipper</td>	
  
	
  	
  	
  	
  	
  	
  <td>1</td>	
  
	
  	
  	
  	
  </tr>	
  
	
  	
  	
  	
  ...	
  
	
  	
  </tbody>	
  
</table>	
  
logs	
  =	
  db().select(db.log.ALL,	
  cache=(cache.disk,	
  60))	
  
Colocando	
  os	
  resultados	
  em	
  Cache	
  
logs	
  =	
  db().select(db.log.ALL,	
  cache=(cache.ram,	
  60))	
  
Retorno	
  como	
  Row	
  object	
  
>>>	
  rows	
  =	
  db(query).select()	
  
Retorno	
  como	
  uma	
  lista	
  
>>>	
  rows_list	
  =	
  rows.as_list()	
  
Retorno	
  como	
  um	
  dicionário	
  
>>>	
  first_row_dict	
  =	
  rows.first().as_dict()	
  
Atalhos	
  
>>>	
  rows	
  =	
  db(query).select()	
  
>>>	
  first_row	
  =	
  rows.first()	
  
>>>	
  last_row	
  =	
  rows.last()	
  
_insert	
  
>>>	
  print	
  db.person._insert(name='Alex')	
  
INSERT	
  INTO	
  person(name)	
  VALUES	
  ('Alex');	
  
Here	
  is	
  _count	
  
_count	
  
>>>	
  print	
  db(db.person.name=='Alex')._count()	
  
SELECT	
  count(*)	
  FROM	
  person	
  WHERE	
  person.name='Alex';	
  
Here	
  is	
  _select	
  
_select	
  
>>>	
  print	
  db(db.person.name=='Alex')._select()	
  
SELECT	
  person.id,	
  person.name	
  FROM	
  person	
  WHERE	
  person.name='Alex';	
  
Here	
  is	
  _delete	
  
_delete	
  
>>>	
  print	
  db(db.person.name=='Alex')._delete()	
  
DELETE	
  FROM	
  person	
  WHERE	
  person.name='Alex';	
  
And	
  finally,	
  here	
  is	
  _update	
  
_update	
  
>>>	
  print	
  db(db.person.name=='Alex')._update()	
  
UPDATE	
  person	
  SET	
  	
  WHERE	
  person.name='Alex';	
  
Exibindo	
  o	
  código	
  SQL	
  	
  
gerado	
  pela	
  DAL	
  
Acessando	
  dados	
  com	
  a	
  DAL	
  em	
  outros	
  projetos	
  PYTHON	
  
Acesso	
  a	
  dados	
  no	
  micro-­‐framework	
  Flask	
  
(Poderia	
  ser	
  Django,	
  Pylons,	
  TurboGears,	
  web.py	
  etc..)	
  
Também	
  poderia	
  ser	
  um	
  script	
  ou	
  um	
  projeto	
  gráfico	
  com	
  
PyQT	
  ou	
  GTK...	
  
Documentação	
  em	
  Português	
  -­‐	
  >	
  h•p://bit.ly/bIy6XZ	
  
Em	
  inglês	
  -­‐	
  >	
  h•p://web2py.com/book	
  	
  	
  
Códigos	
  da	
  aplicação	
  em:	
  
h•ps://bitbucket.org/rochacbruno/dal_on_flask	
  
Bruno	
  C.	
  Rocha	
  
@rochacbruno	
  
h•p://blouweb.com	
  
{{=about_me}}	
  
I	
  work	
  with	
  web	
  development	
  and	
  free	
  soZware.	
  	
  
I	
  create	
  web	
  applicaCons	
  with	
  Python,	
  WEB2PY,	
  Flask,	
  Pylons,	
  
PostGre,	
  MongoDB	
  and	
  Agile	
  methods.	
  	
  
I'm	
  member	
  of	
  the	
  Python	
  community	
  and	
  contribute	
  to	
  the	
  
development	
  and	
  tests	
  of	
  the	
  WEB2PY	
  enterprise	
  web	
  framework.	
  	
  
I	
  offer	
  digital	
  consultancy,	
  couching	
  and	
  training	
  with	
  blouweb	
  
consultoria	
  digital.	
  
I	
  am	
  proudly	
  vegan	
  and	
  animal	
  rights	
  acCvist,	
  married	
  with	
  
@claudiapapp	
  and	
  protector	
  of	
  three	
  dogs	
  ['Joy','Sultão','Chucrute'].	
  
More	
  about	
  me	
  here	
  :	
  h•p://flavors.me/rochacbruno	
  

More Related Content

What's hot

Future of HTTP in CakePHP
Future of HTTP in CakePHPFuture of HTTP in CakePHP
Future of HTTP in CakePHPmarkstory
 
Php unit the-mostunknownparts
Php unit the-mostunknownpartsPhp unit the-mostunknownparts
Php unit the-mostunknownpartsBastian Feder
 
international PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secretsinternational PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secretssmueller_sandsmedia
 
Symfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologySymfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologyDaniel Knell
 
PHP Data Objects
PHP Data ObjectsPHP Data Objects
PHP Data ObjectsWez Furlong
 
Lithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate FrameworksLithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate FrameworksNate Abele
 
Tips of CakePHP and MongoDB - Cakefest2011 ichikaway
Tips of CakePHP and MongoDB - Cakefest2011 ichikaway Tips of CakePHP and MongoDB - Cakefest2011 ichikaway
Tips of CakePHP and MongoDB - Cakefest2011 ichikaway ichikaway
 
Windows power shell and active directory
Windows power shell and active directoryWindows power shell and active directory
Windows power shell and active directoryDan Morrill
 
Doctrine fixtures
Doctrine fixturesDoctrine fixtures
Doctrine fixturesBill Chang
 
Introduction to the new official C# Driver developed by 10gen
Introduction to the new official C# Driver developed by 10genIntroduction to the new official C# Driver developed by 10gen
Introduction to the new official C# Driver developed by 10genMongoDB
 
Opa presentation at GamesJs
Opa presentation at GamesJsOpa presentation at GamesJs
Opa presentation at GamesJsHenri Binsztok
 

What's hot (20)

Quebec pdo
Quebec pdoQuebec pdo
Quebec pdo
 
CakeFest 2013 keynote
CakeFest 2013 keynoteCakeFest 2013 keynote
CakeFest 2013 keynote
 
Future of HTTP in CakePHP
Future of HTTP in CakePHPFuture of HTTP in CakePHP
Future of HTTP in CakePHP
 
Php unit the-mostunknownparts
Php unit the-mostunknownpartsPhp unit the-mostunknownparts
Php unit the-mostunknownparts
 
international PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secretsinternational PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secrets
 
Sqlite perl
Sqlite perlSqlite perl
Sqlite perl
 
Symfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologySymfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technology
 
PHP Data Objects
PHP Data ObjectsPHP Data Objects
PHP Data Objects
 
Agile database access with CakePHP 3
Agile database access with CakePHP 3Agile database access with CakePHP 3
Agile database access with CakePHP 3
 
Doctrine for NoSQL
Doctrine for NoSQLDoctrine for NoSQL
Doctrine for NoSQL
 
Doctrine and NoSQL
Doctrine and NoSQLDoctrine and NoSQL
Doctrine and NoSQL
 
Lithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate FrameworksLithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate Frameworks
 
Tips of CakePHP and MongoDB - Cakefest2011 ichikaway
Tips of CakePHP and MongoDB - Cakefest2011 ichikaway Tips of CakePHP and MongoDB - Cakefest2011 ichikaway
Tips of CakePHP and MongoDB - Cakefest2011 ichikaway
 
Mysql & Php
Mysql & PhpMysql & Php
Mysql & Php
 
Windows power shell and active directory
Windows power shell and active directoryWindows power shell and active directory
Windows power shell and active directory
 
Doctrine fixtures
Doctrine fixturesDoctrine fixtures
Doctrine fixtures
 
Introduction to the new official C# Driver developed by 10gen
Introduction to the new official C# Driver developed by 10genIntroduction to the new official C# Driver developed by 10gen
Introduction to the new official C# Driver developed by 10gen
 
Stored Procedure
Stored ProcedureStored Procedure
Stored Procedure
 
Opa presentation at GamesJs
Opa presentation at GamesJsOpa presentation at GamesJs
Opa presentation at GamesJs
 
Twitter codeigniter library
Twitter codeigniter libraryTwitter codeigniter library
Twitter codeigniter library
 

Viewers also liked

web2py:Web development like a boss
web2py:Web development like a bossweb2py:Web development like a boss
web2py:Web development like a bossFrancisco Ribeiro
 
Plantillas para la creación de material docente accesible con herramientas of...
Plantillas para la creación de material docente accesible con herramientas of...Plantillas para la creación de material docente accesible con herramientas of...
Plantillas para la creación de material docente accesible con herramientas of...Mireia Alcala
 
5-Beamer: Creación de presentaciones con LaTeX
5-Beamer: Creación de presentaciones con LaTeX5-Beamer: Creación de presentaciones con LaTeX
5-Beamer: Creación de presentaciones con LaTeXDigna González
 

Viewers also liked (6)

web2py:Web development like a boss
web2py:Web development like a bossweb2py:Web development like a boss
web2py:Web development like a boss
 
Plantillas para la creación de material docente accesible con herramientas of...
Plantillas para la creación de material docente accesible con herramientas of...Plantillas para la creación de material docente accesible con herramientas of...
Plantillas para la creación de material docente accesible con herramientas of...
 
LaTeX sin dolor.
LaTeX sin dolor.LaTeX sin dolor.
LaTeX sin dolor.
 
5-Beamer: Creación de presentaciones con LaTeX
5-Beamer: Creación de presentaciones con LaTeX5-Beamer: Creación de presentaciones con LaTeX
5-Beamer: Creación de presentaciones con LaTeX
 
Gestión de datos de investigación: trabajo cooperativo en las bibliotecas de ...
Gestión de datos de investigación: trabajo cooperativo en las bibliotecas de ...Gestión de datos de investigación: trabajo cooperativo en las bibliotecas de ...
Gestión de datos de investigación: trabajo cooperativo en las bibliotecas de ...
 
Latex - Creación de documentos cientificos
Latex - Creación de documentos cientificosLatex - Creación de documentos cientificos
Latex - Creación de documentos cientificos
 

Similar to Using web2py's DAL in other projects or frameworks

Deeply Declarative Data Pipelines
Deeply Declarative Data PipelinesDeeply Declarative Data Pipelines
Deeply Declarative Data PipelinesHostedbyConfluent
 
Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)
Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)
Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)MongoSF
 
How to Bring Common UI Patterns to ADF
How to Bring Common UI Patterns to ADF How to Bring Common UI Patterns to ADF
How to Bring Common UI Patterns to ADF Luc Bors
 
Database API, your new friend
Database API, your new friendDatabase API, your new friend
Database API, your new friendkikoalonsob
 
Nosql hands on handout 04
Nosql hands on handout 04Nosql hands on handout 04
Nosql hands on handout 04Krishna Sankar
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with ClojureDmitry Buzdin
 
Ex[1].3 php db connectivity
Ex[1].3 php db connectivityEx[1].3 php db connectivity
Ex[1].3 php db connectivityMouli Chandira
 
Store and Process Big Data with Hadoop and Cassandra
Store and Process Big Data with Hadoop and CassandraStore and Process Big Data with Hadoop and Cassandra
Store and Process Big Data with Hadoop and CassandraDeependra Ariyadewa
 
Python postgre sql a wonderful wedding
Python postgre sql   a wonderful weddingPython postgre sql   a wonderful wedding
Python postgre sql a wonderful weddingStéphane Wirtel
 
Hadoop Integration in Cassandra
Hadoop Integration in CassandraHadoop Integration in Cassandra
Hadoop Integration in CassandraJairam Chandar
 
Hibernate
Hibernate Hibernate
Hibernate Sunil OS
 
All Things Open 2016 -- Database Programming for Newbies
All Things Open 2016 -- Database Programming for NewbiesAll Things Open 2016 -- Database Programming for Newbies
All Things Open 2016 -- Database Programming for NewbiesDave Stokes
 
Cassandra Summit 2013 Keynote
Cassandra Summit 2013 KeynoteCassandra Summit 2013 Keynote
Cassandra Summit 2013 Keynotejbellis
 

Similar to Using web2py's DAL in other projects or frameworks (20)

Deeply Declarative Data Pipelines
Deeply Declarative Data PipelinesDeeply Declarative Data Pipelines
Deeply Declarative Data Pipelines
 
Databases with SQLite3.pdf
Databases with SQLite3.pdfDatabases with SQLite3.pdf
Databases with SQLite3.pdf
 
How te bring common UI patterns to ADF
How te bring common UI patterns to ADFHow te bring common UI patterns to ADF
How te bring common UI patterns to ADF
 
3 database-jdbc(1)
3 database-jdbc(1)3 database-jdbc(1)
3 database-jdbc(1)
 
Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)
Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)
Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)
 
How to Bring Common UI Patterns to ADF
How to Bring Common UI Patterns to ADF How to Bring Common UI Patterns to ADF
How to Bring Common UI Patterns to ADF
 
Database API, your new friend
Database API, your new friendDatabase API, your new friend
Database API, your new friend
 
Python database access
Python database accessPython database access
Python database access
 
Nosql hands on handout 04
Nosql hands on handout 04Nosql hands on handout 04
Nosql hands on handout 04
 
Sql
SqlSql
Sql
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
 
MySql slides (ppt)
MySql slides (ppt)MySql slides (ppt)
MySql slides (ppt)
 
Ex[1].3 php db connectivity
Ex[1].3 php db connectivityEx[1].3 php db connectivity
Ex[1].3 php db connectivity
 
Couchdb
CouchdbCouchdb
Couchdb
 
Store and Process Big Data with Hadoop and Cassandra
Store and Process Big Data with Hadoop and CassandraStore and Process Big Data with Hadoop and Cassandra
Store and Process Big Data with Hadoop and Cassandra
 
Python postgre sql a wonderful wedding
Python postgre sql   a wonderful weddingPython postgre sql   a wonderful wedding
Python postgre sql a wonderful wedding
 
Hadoop Integration in Cassandra
Hadoop Integration in CassandraHadoop Integration in Cassandra
Hadoop Integration in Cassandra
 
Hibernate
Hibernate Hibernate
Hibernate
 
All Things Open 2016 -- Database Programming for Newbies
All Things Open 2016 -- Database Programming for NewbiesAll Things Open 2016 -- Database Programming for Newbies
All Things Open 2016 -- Database Programming for Newbies
 
Cassandra Summit 2013 Keynote
Cassandra Summit 2013 KeynoteCassandra Summit 2013 Keynote
Cassandra Summit 2013 Keynote
 

More from Bruno Rocha

Escrevendo modulos python com rust
Escrevendo modulos python com rustEscrevendo modulos python com rust
Escrevendo modulos python com rustBruno Rocha
 
The quality of the python ecosystem - and how we can protect it!
The quality of the python ecosystem - and how we can protect it!The quality of the python ecosystem - and how we can protect it!
The quality of the python ecosystem - and how we can protect it!Bruno Rocha
 
A Qualidade do Ecossistema Python - e o que podemos fazer para mante-la
A Qualidade do Ecossistema Python - e o que podemos fazer para mante-laA Qualidade do Ecossistema Python - e o que podemos fazer para mante-la
A Qualidade do Ecossistema Python - e o que podemos fazer para mante-laBruno Rocha
 
PyData - Consumindo e publicando web APIs com Python
PyData - Consumindo e publicando web APIs com PythonPyData - Consumindo e publicando web APIs com Python
PyData - Consumindo e publicando web APIs com PythonBruno Rocha
 
Quokka CMS - Desenvolvendo web apps com Flask e MongoDB - grupy - Outubro 2015
Quokka CMS - Desenvolvendo web apps com Flask e MongoDB - grupy - Outubro 2015Quokka CMS - Desenvolvendo web apps com Flask e MongoDB - grupy - Outubro 2015
Quokka CMS - Desenvolvendo web apps com Flask e MongoDB - grupy - Outubro 2015Bruno Rocha
 
Data Developer - Engenharia de Dados em um time de Data Science - Uai python2015
Data Developer - Engenharia de Dados em um time de Data Science - Uai python2015Data Developer - Engenharia de Dados em um time de Data Science - Uai python2015
Data Developer - Engenharia de Dados em um time de Data Science - Uai python2015Bruno Rocha
 
Python Flask app deployed to OPenShift using Wercker CI
Python Flask app deployed to OPenShift using Wercker CIPython Flask app deployed to OPenShift using Wercker CI
Python Flask app deployed to OPenShift using Wercker CIBruno Rocha
 
Carreira de Programador e Mercado de Trabalho
Carreira de Programador e Mercado de TrabalhoCarreira de Programador e Mercado de Trabalho
Carreira de Programador e Mercado de TrabalhoBruno Rocha
 
Quokka CMS - Content Management with Flask and Mongo #tdc2014
Quokka CMS - Content Management with Flask and Mongo #tdc2014Quokka CMS - Content Management with Flask and Mongo #tdc2014
Quokka CMS - Content Management with Flask and Mongo #tdc2014Bruno Rocha
 
Web Crawling Modeling with Scrapy Models #TDC2014
Web Crawling Modeling with Scrapy Models #TDC2014Web Crawling Modeling with Scrapy Models #TDC2014
Web Crawling Modeling with Scrapy Models #TDC2014Bruno Rocha
 
Flask for CMS/App Framework development.
Flask for CMS/App Framework development.Flask for CMS/App Framework development.
Flask for CMS/App Framework development.Bruno Rocha
 
What The Flask? and how to use it with some Google APIs
What The Flask? and how to use it with some Google APIsWhat The Flask? and how to use it with some Google APIs
What The Flask? and how to use it with some Google APIsBruno Rocha
 
Desenvolvendo mvp com python
Desenvolvendo mvp com pythonDesenvolvendo mvp com python
Desenvolvendo mvp com pythonBruno Rocha
 
Flask Full Stack - Desenvolvendo um CMS com Flask e MongoDB
Flask Full Stack - Desenvolvendo um CMS com Flask e MongoDBFlask Full Stack - Desenvolvendo um CMS com Flask e MongoDB
Flask Full Stack - Desenvolvendo um CMS com Flask e MongoDBBruno Rocha
 
Django para portais de alta visibilidade. tdc 2013
Django para portais de alta visibilidade.   tdc 2013Django para portais de alta visibilidade.   tdc 2013
Django para portais de alta visibilidade. tdc 2013Bruno Rocha
 
Guia alimentar de dietas vegetarianas para adultos
Guia alimentar de dietas vegetarianas para adultosGuia alimentar de dietas vegetarianas para adultos
Guia alimentar de dietas vegetarianas para adultosBruno Rocha
 
Desmistificando web2py - #TDC2011
Desmistificando web2py - #TDC2011Desmistificando web2py - #TDC2011
Desmistificando web2py - #TDC2011Bruno Rocha
 
Desenvolvimento web ágil com Python e web2py #qconsp #qcon
Desenvolvimento web ágil com Python e web2py #qconsp #qconDesenvolvimento web ágil com Python e web2py #qconsp #qcon
Desenvolvimento web ágil com Python e web2py #qconsp #qconBruno Rocha
 

More from Bruno Rocha (18)

Escrevendo modulos python com rust
Escrevendo modulos python com rustEscrevendo modulos python com rust
Escrevendo modulos python com rust
 
The quality of the python ecosystem - and how we can protect it!
The quality of the python ecosystem - and how we can protect it!The quality of the python ecosystem - and how we can protect it!
The quality of the python ecosystem - and how we can protect it!
 
A Qualidade do Ecossistema Python - e o que podemos fazer para mante-la
A Qualidade do Ecossistema Python - e o que podemos fazer para mante-laA Qualidade do Ecossistema Python - e o que podemos fazer para mante-la
A Qualidade do Ecossistema Python - e o que podemos fazer para mante-la
 
PyData - Consumindo e publicando web APIs com Python
PyData - Consumindo e publicando web APIs com PythonPyData - Consumindo e publicando web APIs com Python
PyData - Consumindo e publicando web APIs com Python
 
Quokka CMS - Desenvolvendo web apps com Flask e MongoDB - grupy - Outubro 2015
Quokka CMS - Desenvolvendo web apps com Flask e MongoDB - grupy - Outubro 2015Quokka CMS - Desenvolvendo web apps com Flask e MongoDB - grupy - Outubro 2015
Quokka CMS - Desenvolvendo web apps com Flask e MongoDB - grupy - Outubro 2015
 
Data Developer - Engenharia de Dados em um time de Data Science - Uai python2015
Data Developer - Engenharia de Dados em um time de Data Science - Uai python2015Data Developer - Engenharia de Dados em um time de Data Science - Uai python2015
Data Developer - Engenharia de Dados em um time de Data Science - Uai python2015
 
Python Flask app deployed to OPenShift using Wercker CI
Python Flask app deployed to OPenShift using Wercker CIPython Flask app deployed to OPenShift using Wercker CI
Python Flask app deployed to OPenShift using Wercker CI
 
Carreira de Programador e Mercado de Trabalho
Carreira de Programador e Mercado de TrabalhoCarreira de Programador e Mercado de Trabalho
Carreira de Programador e Mercado de Trabalho
 
Quokka CMS - Content Management with Flask and Mongo #tdc2014
Quokka CMS - Content Management with Flask and Mongo #tdc2014Quokka CMS - Content Management with Flask and Mongo #tdc2014
Quokka CMS - Content Management with Flask and Mongo #tdc2014
 
Web Crawling Modeling with Scrapy Models #TDC2014
Web Crawling Modeling with Scrapy Models #TDC2014Web Crawling Modeling with Scrapy Models #TDC2014
Web Crawling Modeling with Scrapy Models #TDC2014
 
Flask for CMS/App Framework development.
Flask for CMS/App Framework development.Flask for CMS/App Framework development.
Flask for CMS/App Framework development.
 
What The Flask? and how to use it with some Google APIs
What The Flask? and how to use it with some Google APIsWhat The Flask? and how to use it with some Google APIs
What The Flask? and how to use it with some Google APIs
 
Desenvolvendo mvp com python
Desenvolvendo mvp com pythonDesenvolvendo mvp com python
Desenvolvendo mvp com python
 
Flask Full Stack - Desenvolvendo um CMS com Flask e MongoDB
Flask Full Stack - Desenvolvendo um CMS com Flask e MongoDBFlask Full Stack - Desenvolvendo um CMS com Flask e MongoDB
Flask Full Stack - Desenvolvendo um CMS com Flask e MongoDB
 
Django para portais de alta visibilidade. tdc 2013
Django para portais de alta visibilidade.   tdc 2013Django para portais de alta visibilidade.   tdc 2013
Django para portais de alta visibilidade. tdc 2013
 
Guia alimentar de dietas vegetarianas para adultos
Guia alimentar de dietas vegetarianas para adultosGuia alimentar de dietas vegetarianas para adultos
Guia alimentar de dietas vegetarianas para adultos
 
Desmistificando web2py - #TDC2011
Desmistificando web2py - #TDC2011Desmistificando web2py - #TDC2011
Desmistificando web2py - #TDC2011
 
Desenvolvimento web ágil com Python e web2py #qconsp #qcon
Desenvolvimento web ágil com Python e web2py #qconsp #qconDesenvolvimento web ágil com Python e web2py #qconsp #qcon
Desenvolvimento web ágil com Python e web2py #qconsp #qcon
 

Recently uploaded

H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DaySri Ambati
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 

Recently uploaded (20)

H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 

Using web2py's DAL in other projects or frameworks

  • 1. DAL! Database Abstraction Layer! Utilizando as classes de acesso a dados do WEB2PY em outros projetos Python.!
  • 3. ORM!X! “DAL  é  uma  API  que  mapeia  objetos  Python  em  objetos  de   banco  de  dados  como  queries,  tabelas,  e  registros.  A  DAL   gera  códigos  SQL  dinâmicamente  em  tempo  real  uClizando   sempre  o  dialeto  SQL  referente  ao  banco  de  dados  em  uso”   -­‐ Massimo  Di  Pierro  -­‐  web2py.com/book  
  • 4. Request   Conexão,  modelagem   DAL   (Model)   DATABASE  –  SQL/GQL   http://twit2py.com/timeline/rochacbruno from gluon.sql import DAL,Field, Table db = DAL(‘postgres://username:password@host/db’) utline = db.define_table(‘usertimeline’, Field(‘user’), Field(‘tweet’), Field(‘timestamp’,’datetime’), migrate=True) SELECT user, tweet, timestamp FROM usertimeline WHERE user = ‘rochacbruno’ ORDER BY timestamp desc DAL  queries   (Controller)   def timeline(): user = request.args[0] query = utline.user==user order = utline.timestamp rows = db(query).select(orderby=~order) return dict(timeline=rows) Globals()   Output   Response   (view)   {‘timeline’:rows} for tweet in timeline: DO SOMETHING
  • 5. • SQLite   • PostgreSQL   • MySQL   • Oracle   • MicrosoZ  SQL  Server   • FireBird   • DB2   • Informix   • Ingres.   • Google  BigTable   • Google  App  Engine  (GAE)   • JDBC  +  executesql  
  • 6.
  • 7. from  gluon.sql  import  DAL,  Field,  Table   • Load  Balance   • Replicação  de  dados   • Conexões  simultâneas  a  diversos  bancos  de  dados   • ConnecCon  Pooling   • Migrações  AutomáCcas   • Parsing  (Json,  CSV,  list,  dict)   • Import  e  Export  -­‐  CSV   • Constraints   • TransacCons   • CRUD  (  Queries,  Sets,  Joins,  Like,  Belongs....)   • Computed  Fields   • Virtual  Fields   • Traversing   • More....  
  • 8. db  =  DAL(['mysql://host1','mysql://host2','mysql://host3'])   db  =  DAL('sqlite://storage.db’,  check_reserved=['postgres',  'mssql’,’commom’,’all’])   Replicação  /  FailOver   Palavras  reservadas   db  =  DAL('mysql://host1’,pool_size=10)   Connec6on  Pooling   >>>  print  db.executesql('SELECT  *  FROM  person;')   [(1,  u’José'),  (2,  u’Mickael')]   Last_sql   >>>  rows  =  db().select(db.person.ALL)   >>>  print  db._lastsql   SELECT  person.id,  person.name  FROM  person;   Raw_sql  
  • 9. Distributed  Transac6on   db_a  =  DAL('postgres://...')   db_b  =  DAL('postgres://...')   DAL.distributed_transacCon_commit(db_a,  db_b)   db.commit()   db.rollback()   Transac6ons   DAL.distributed_transacCon_rollback(db_a,  db_b)  
  • 10. Exportar  o  banco  de  dados  para  CSV   >>>  db.export_to_csv_file(open('somefile.csv',  'wb'))   Importar  o  banco  de  dados  de  um  CSV   >>>  db.import_from_csv_file(open('somefile.csv',  'rb'))   Somefile.CSV   TABLE  person   person.id,person.name,person.language   1,Claudia,Python   2,Bruno,Python   TABLE  dog   dog.id,dog.name,dog.owner,dog.age,dog.realage   1,chucrute,2,10,70.0   2,Joy,1,2,14.0   3,Pimenta,1,1,7.0   4,Sultao,2,8,56.0   END  
  • 11. Retorno  do  db  como  XML  ou  JSON   >>>  rows  =  db(db.person.id  >  0).select()   >>>  print  rows.xml()  #  could  be  rows.json()   <table>      <thead>          <tr>              <th>person.id</th>              <th>person.name</th>   </tr>      </thead>      <tbody>          <tr  class="even">              <td>1</td>              <td>Alex</td>              <td>1</td>              <td>Skipper</td>              <td>1</td>          </tr>          ...      </tbody>   </table>  
  • 12. logs  =  db().select(db.log.ALL,  cache=(cache.disk,  60))   Colocando  os  resultados  em  Cache   logs  =  db().select(db.log.ALL,  cache=(cache.ram,  60))  
  • 13. Retorno  como  Row  object   >>>  rows  =  db(query).select()   Retorno  como  uma  lista   >>>  rows_list  =  rows.as_list()   Retorno  como  um  dicionário   >>>  first_row_dict  =  rows.first().as_dict()   Atalhos   >>>  rows  =  db(query).select()   >>>  first_row  =  rows.first()   >>>  last_row  =  rows.last()  
  • 14. _insert   >>>  print  db.person._insert(name='Alex')   INSERT  INTO  person(name)  VALUES  ('Alex');   Here  is  _count   _count   >>>  print  db(db.person.name=='Alex')._count()   SELECT  count(*)  FROM  person  WHERE  person.name='Alex';   Here  is  _select   _select   >>>  print  db(db.person.name=='Alex')._select()   SELECT  person.id,  person.name  FROM  person  WHERE  person.name='Alex';   Here  is  _delete   _delete   >>>  print  db(db.person.name=='Alex')._delete()   DELETE  FROM  person  WHERE  person.name='Alex';   And  finally,  here  is  _update   _update   >>>  print  db(db.person.name=='Alex')._update()   UPDATE  person  SET    WHERE  person.name='Alex';   Exibindo  o  código  SQL     gerado  pela  DAL  
  • 15. Acessando  dados  com  a  DAL  em  outros  projetos  PYTHON   Acesso  a  dados  no  micro-­‐framework  Flask   (Poderia  ser  Django,  Pylons,  TurboGears,  web.py  etc..)   Também  poderia  ser  um  script  ou  um  projeto  gráfico  com   PyQT  ou  GTK...  
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24. Documentação  em  Português  -­‐  >  h•p://bit.ly/bIy6XZ   Em  inglês  -­‐  >  h•p://web2py.com/book       Códigos  da  aplicação  em:   h•ps://bitbucket.org/rochacbruno/dal_on_flask  
  • 25. Bruno  C.  Rocha   @rochacbruno   h•p://blouweb.com   {{=about_me}}   I  work  with  web  development  and  free  soZware.     I  create  web  applicaCons  with  Python,  WEB2PY,  Flask,  Pylons,   PostGre,  MongoDB  and  Agile  methods.     I'm  member  of  the  Python  community  and  contribute  to  the   development  and  tests  of  the  WEB2PY  enterprise  web  framework.     I  offer  digital  consultancy,  couching  and  training  with  blouweb   consultoria  digital.   I  am  proudly  vegan  and  animal  rights  acCvist,  married  with   @claudiapapp  and  protector  of  three  dogs  ['Joy','Sultão','Chucrute'].   More  about  me  here  :  h•p://flavors.me/rochacbruno