using web2py's dal in other projects or frameworks

25
DAL Database Abstraction Layer Utilizando as classes de acesso a dados do WEB2PY em outros projetos Python.

Upload: bruno-rocha

Post on 01-Nov-2014

4.137 views

Category:

Technology


4 download

DESCRIPTION

#pythonbrasilComo usar a DAL do web2py em outros projetos e frameworks Python.

TRANSCRIPT

Page 1: Using web2py's DAL in other projects or frameworks

DAL!Database Abstraction Layer !

Utilizando as classes de acesso a dados do WEB2PY em outros projetos Python.!

Page 2: Using web2py's DAL in other projects or frameworks

ORM!

Page 3: Using web2py's DAL in other projects or frameworks

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  

Page 4: Using web2py's DAL in other projects or frameworks

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 usertimelineWHERE 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

Page 5: Using web2py's DAL in other projects or frameworks

• SQLite  • PostgreSQL  • MySQL  • Oracle  • MicrosoZ  SQL  Server  • FireBird  • DB2  • Informix  • Ingres.  • Google  BigTable  • Google  App  Engine  (GAE)  • JDBC  +  executesql  

Page 6: Using web2py's DAL in other projects or frameworks
Page 7: Using web2py's DAL in other projects or frameworks

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....  

Page 8: Using web2py's DAL in other projects or frameworks

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  

Page 9: Using web2py's DAL in other projects or frameworks

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)  

Page 10: Using web2py's DAL in other projects or frameworks

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  

Page 11: Using web2py's DAL in other projects or frameworks

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>  

Page 12: Using web2py's DAL in other projects or frameworks

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

Page 13: Using web2py's DAL in other projects or frameworks

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

Page 14: Using web2py's DAL in other projects or frameworks

_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  

Page 15: Using web2py's DAL in other projects or frameworks

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...  

Page 16: Using web2py's DAL in other projects or frameworks
Page 17: Using web2py's DAL in other projects or frameworks
Page 18: Using web2py's DAL in other projects or frameworks
Page 19: Using web2py's DAL in other projects or frameworks
Page 20: Using web2py's DAL in other projects or frameworks
Page 21: Using web2py's DAL in other projects or frameworks
Page 22: Using web2py's DAL in other projects or frameworks
Page 23: Using web2py's DAL in other projects or frameworks
Page 24: Using web2py's DAL in other projects or frameworks

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  

Page 25: Using web2py's DAL in other projects or frameworks

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