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