Header Ads

web.py com SQLObject

O SQLObject é um excelente ORM (Object Relational Manager/Mapper) e sua utilização com o web.py é bem fácil:


Em teu arquivo code.py:

 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#!/usr/bin/env python

import string
import random

import web

from models import *

urls = (
"/", "add",
"/view", "view"
)

def load_sqlo(handler=None):
con = connectionForURI('sqlite:mydatabase.db')
if not web.ctx.has_key('env'): # not using web.py
sqlhub.processConnection = con
return
trans = con.transaction()
sqlhub.threadConnection = trans
try:
return handler()
except web.HTTPError:
trans.commit(close=True)
raise
except:
trans.rollback()
trans.begin()
raise
finally:
trans.commit(close=True)

app = web.application(urls, locals())
app.add_processor(load_sqlo)


class add:
def GET(self):
web.header('Content-type', 'text/html')
fname = "".join(random.choice(string.letters) for i in range(4))
lname = "".join(random.choice(string.letters) for i in range(7))
u = User(name=fname
,fullname=fname + ' ' + lname
,password='542')
return "added:" + web.websafe(str(u)) \
+ "<br/>" \
+ '<a href="/view">view all</a>'

class view:
def GET(self):
web.header('Content-type', 'text/plain')
return "\n".join(map(str, User.select()))


if __name__ == "__main__":
app.run()


Em teu arquivo model.py:


 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
from sqlobject import *

sqlhub.processConnection = connectionForURI('sqlite:mydatabase.db')

class User(SQLObject):

class sqlmeta:

table = 'users'

name = StringCol()
fullname = StringCol()
password = StringCol()

if __name__ == "__main__":
User.dropTable(ifExists=True)
User.createTable()


Fonte: https://github.com/RhubarbSin/example-sqlobject-webpy

Nenhum comentário