-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase.py
More file actions
78 lines (65 loc) · 2.07 KB
/
Copy pathdatabase.py
File metadata and controls
78 lines (65 loc) · 2.07 KB
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
67
68
69
70
71
72
73
74
75
76
77
78
# -*- coding: utf-8 -*-
#
# Author: jimin.huang
#
'''
The singleton database connection. Every action of database would
create a new connection if no connection is created before or use the exis-
ted one.
Also the decorator catch all raised exception during the connection. Once a
exception is raised, it logs an error message and sends alert emails to all
users in the alert list.
To use the connection in the function, you should decorate your function w-
ith ``get_connection``
::
@classmethod
@get_connection
def your_function(cls, connection, *args):
pass
.. note::
The decorated function must be a class method!
Methods
------------------------
'''
import torndb
import logging
import email_sender
from tornado.options import options
# TODO: Choose different modules depending on the type of database.
def get_connection(function):
'''
The decorator with a singleton connection of database.
'''
def wrapper(cls, *args, **kwargs):
try:
connection =\
torndb.Connection(
":".join(
[
options.database_address,
options.database_port,
]
),
cls.db,
options.database_user,
options.database_password,
)
return function(cls, connection, *args, **kwargs)
except Exception, e:
# Log error
logging.error(
(
'Mysql Connection Error: '
'Occured when class {0} try to build connection'
).format(
cls.__name__
)
)
# Send alert email
message = str(e)
email_sender.async_send(
title="The Exception Raised",
message=message
)
return None if 'query' not in function.__name__ else []
return wrapper