Browse Source

Moved the MongoDb database connection method to the utils module

Roland Haroutiounian 8 years ago
parent
commit
7ea8470089
2 changed files with 51 additions and 34 deletions
  1. 2
    34
      lodel/datasource/mongodb/datasource.py
  2. 49
    0
      lodel/datasource/mongodb/utils.py

+ 2
- 34
lodel/datasource/mongodb/datasource.py View File

4
 from bson.son import SON
4
 from bson.son import SON
5
 from collections import OrderedDict
5
 from collections import OrderedDict
6
 import pymongo
6
 import pymongo
7
-from pymongo import MongoClient
7
+# from pymongo import MongoClient
8
 from pymongo.errors import BulkWriteError
8
 from pymongo.errors import BulkWriteError
9
 import urllib
9
 import urllib
10
 
10
 
19
 
19
 
20
 class MongoDbDataSource(GenericDataSource):
20
 class MongoDbDataSource(GenericDataSource):
21
 
21
 
22
-    MANDATORY_CONNECTION_ARGS = ('host', 'port', 'login', 'password', 'dbname')
23
-
24
     ## @brief Instanciates a Database object given a connection name
22
     ## @brief Instanciates a Database object given a connection name
25
     # @param connection_name str
23
     # @param connection_name str
26
     def __init__(self, connection_name='default'):
24
     def __init__(self, connection_name='default'):
27
-        connection_args = self._get_connection_args(connection_name)
28
-        login, password, host, port, dbname = MongoDbDataSource._check_connection_args(connection_args)
29
-
30
-        # Creating of the connection
31
-        connection_string = 'mongodb://%s:%s@%s:%s' % (login, password, host, port)
32
-        self.connection = MongoClient(connection_string)
33
-        # Getting the database
34
-        self.database = self.connection[dbname]
35
-
36
-    ## @brief Gets the settings given a connection name
37
-    # @param connection_name str
38
-    # @return dict
39
-    # @TODO Change the return value using the Lodel 2 settings module
40
-    def _get_connection_args(self, connection_name):
41
-        return {'host': 'localhost', 'port': 28015, 'login': 'lodel_admin', 'password': 'lapwd', 'dbname': 'lodel'}
42
-
43
-    ## @brief checks if the connection args are valid and complete
44
-    # @param connection_args dict
45
-    # @return bool
46
-    # @todo checks on the argument types can be added here
47
-    @classmethod
48
-    def _check_connection_args(cls, connection_args):
49
-        errors = []
50
-        for connection_arg in cls.MANDATORY_CONNECTION_ARGS:
51
-            if connection_arg not in connection_args:
52
-                errors.append("Datasource connection error : %s parameter is missing." % connection_arg)
53
-        if len(errors) > 0 :
54
-            raise MongoDbDataSourceError("\r\n-".join(errors))
55
-
56
-        return (connection_args['login'], connection_args['password'], connection_args['host'],
57
-                connection_args['port'], connection_args['dbname'])
25
+        self.database = utils.mongodbconnect(connection_name)
58
 
26
 
59
     ## @brief returns a selection of documents from the datasource
27
     ## @brief returns a selection of documents from the datasource
60
     # @param target_cls Emclass
28
     # @param target_cls Emclass

+ 49
- 0
lodel/datasource/mongodb/utils.py View File

1
 # -*- coding: utf-8 -*-
1
 # -*- coding: utf-8 -*-
2
 
2
 
3
 import pymongo
3
 import pymongo
4
+from pymongo import MongoClient
4
 
5
 
5
 common_collections = {
6
 common_collections = {
6
     'object': 'object'
7
     'object': 'object'
35
 }
36
 }
36
 
37
 
37
 
38
 
39
+MANDATORY_CONNECTION_ARGS = ('host', 'port', 'login', 'password', 'dbname')
40
+
41
+
42
+class MongoDbConnectionError(Exception):
43
+    pass
44
+
45
+
46
+## @brief Creates a connection to a MongoDb database
47
+def mongodbconnect(connection_name):
48
+    connection_args = get_connection_args(connection_name)
49
+    checked_connection_args = check_connection_args(connection_args)
50
+    if len(checked_connection_args['errors']) > 0:
51
+        raise MongoDbConnectionError("\r\n-".join(checked_connection_args['errors']))
52
+
53
+    # connection arguments are parsed after the check
54
+    login, password, host, port, dbname = checked_connection_args['params']
55
+
56
+    # Connection creation
57
+    connection_string = 'mongodb://%s:%s@%s:%s' % (login, password, host, port)
58
+    connection = MongoClient(connection_string)
59
+
60
+    # Setting the database
61
+    database = connection[dbname]
62
+
63
+    return database
64
+
65
+
66
+## @brief gets the settings given a connection name
67
+# @param connection_name str
68
+# @return dict
69
+# @todo connect this method to the settings
70
+def get_connection_args(connnection_name):
71
+    return {'host': 'localhost', 'port': 28015, 'login': 'lodel_admin', 'password': 'lapwd', 'dbname': 'lodel'}
72
+
73
+
74
+## @brief Checks the settings given a connection name
75
+# @param connection_args dict
76
+# @return dict
77
+# @throw MongoDbDataSourceError with the list of all the found errors
78
+# @todo optimize the error management
79
+def check_connection_args(connection_args):
80
+    check_result = {'params': connection_args, 'errors': []}
81
+    for connection_arg in MANDATORY_CONNECTION_ARGS:
82
+        if connection_arg not in connection_args:
83
+            check_result['errors'].append('Datasource connection error: %s parameter is missing.' % connection_arg)
84
+    return check_result
85
+
86
+
38
 ## @brief Returns a collection name given a Emclass name
87
 ## @brief Returns a collection name given a Emclass name
39
 # @param class_name str : The class name
88
 # @param class_name str : The class name
40
 # @return str
89
 # @return str

Loading…
Cancel
Save