forked from iceone/momoko
-
Notifications
You must be signed in to change notification settings - Fork 0
/
blocking_client.py
66 lines (53 loc) · 1.71 KB
/
blocking_client.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
58
59
60
61
62
63
64
65
66
#!/usr/bin/env python
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
import momoko
class BaseHandler(tornado.web.RequestHandler):
@property
def db(self):
# Create a database connection when a request handler is called
# and store the connection in the application object.
if not hasattr(self.application, 'db'):
self.application.db = momoko.BlockingClient({
'host': 'localhost',
'database': 'momoko',
'user': 'frank',
'password': '',
'min_conn': 1,
'max_conn': 20,
'cleanup_timeout': 10
})
return self.application.db
class OverviewHandler(BaseHandler):
def get(self):
self.write('''
<ul>
<li><a href="/query">A single query</a></li>
</ul>
''')
self.finish()
class SingleQueryHandler(BaseHandler):
def get(self):
# Besides using a with statement everyting is the same as the normal
# Psycopg2 module
with self.db.connection as conn:
cursor = conn.cursor()
cursor.execute('SELECT 42, 12, 40, 11;')
self.write('Query results: %s' % cursor.fetchall())
self.finish()
def main():
try:
tornado.options.parse_command_line()
application = tornado.web.Application([
(r'/', OverviewHandler),
(r'/query', SingleQueryHandler)
], debug=True)
http_server = tornado.httpserver.HTTPServer(application)
http_server.listen(8888)
tornado.ioloop.IOLoop.instance().start()
except KeyboardInterrupt:
print('Exit')
if __name__ == '__main__':
main()