Test Failed
Push — master ( 504214...a7ebe7 )
by Alex
02:02
created

snakelet.storage.manager.Manager.find_one()   A

Complexity

Conditions 1

Size

Total Lines 9
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nop 3
dl 0
loc 9
rs 9.6666
c 0
b 0
f 0
1
import inspect
0 ignored issues
show
Coding Style introduced by
This module should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
2
3
from bson.dbref import DBRef
0 ignored issues
show
introduced by
Unable to import 'bson.dbref'
Loading history...
4
from pymongo import MongoClient
0 ignored issues
show
introduced by
Unable to import 'pymongo'
Loading history...
5
6
from .collection import Collection
7
from .document import Document
8
from ..utilities.conversion import Conversion
9
10
11
class Manager(object):
0 ignored issues
show
Coding Style introduced by
This class should have a docstring.

The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:

class SomeClass:
    def some_method(self):
        """Do x and return foo."""

If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.

Loading history...
Unused Code introduced by
The variable __class__ seems to be unused.
Loading history...
12
13
    def __init__(self, database, host=None, port=None, username=None, password=None, case=None):
0 ignored issues
show
best-practice introduced by
Too many arguments (7/5)
Loading history...
14
        """
15
        :param database:
16
        :param host:
17
        :param port:
18
        :param username:
19
        :param password:
20
        :param case:
21
        """
22
        # Configuration
23
        self.collection_name = Conversion(case)
24
        self.document_name = Conversion('camel')
25
26
        # Driver
27
        self.client = MongoClient(host=host, port=port)
28
        self.client[database].authenticate(name=username, password=password)
29
        self.db = self.client[database]
0 ignored issues
show
Coding Style Naming introduced by
The name db does not conform to the attribute naming conventions ((([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$).

This check looks for invalid names for a range of different identifiers.

You can set regular expressions to which the identifiers must conform if the defaults do not match your requirements.

If your project includes a Pylint configuration file, the settings contained in that file take precedence.

To find out more about Pylint, please refer to their site.

Loading history...
30
31
        # Storage
32
        self.collections = {}
33
        self.documents = {}
34
        self.ref_types = (dict, list, DBRef)
35
36
    @staticmethod
37
    def identify(document):
38
        """
39
        Args:
40
            document:
41
42
        Returns:
43
            str: Name of document
44
        """
45
        isclass = inspect.isclass(document)
46
        if isclass and issubclass(document, Document):
47
            return document.__name__
48
        elif not isclass and isinstance(document, Document):
49
            return type(document).__name__
50
        else:
51
            raise TypeError('Value is not an instance or subclass of Document.')
52
53
    def collection(self, target):
54
        """
55
        Args:
56
            target:
57
58
        Returns:
59
            Collection:
60
        """
61
        if not isinstance(target, str):
62
            target = self.identify(target)
63
        if target not in self.collections:
64
            raise LookupError('Collection ' + target + ' does not exist.')
65
        return self.collections[target]
66
67
    def register(self, *args):
68
        """
69
        Args:
70
            *args: One or more documents
71
72
        Returns:
73
74
        """
75
        for document in args:
76
            if not issubclass(document, Document):
77
                continue
78
            identifier = self.identify(document)
79
            if identifier in self.documents:
80
                raise LookupError('Document ' + identifier + ' is already registered.')
81
            self.documents[identifier] = document
82
            self.collections[identifier] = Collection(self, document)
83
            self.__setattr__(identifier, Collection(self, document))
84
85
    def objectify(self, collection, document):
86
        """
87
        Args:
88
            collection:
89
            document:
90
91
        Returns:
92
            Document:
93
        """
94
        # TODO: This should probably access the correct collection instead
0 ignored issues
show
Coding Style introduced by
TODO and FIXME comments should generally be avoided.
Loading history...
95
        name = self.document_name.encode(collection)
96
        if name in self.documents:
97
            prototype = self.documents[name]()
98
            if document:
99
                prototype.update(document)
100
            # TODO: There needs to be a 'proxy' object that holds the DBRef and hydrates
0 ignored issues
show
Coding Style introduced by
TODO and FIXME comments should generally be avoided.
Loading history...
101
            # self.hydrate(prototype)
102
            return prototype
103
        return document
104
105
    def hydrate(self, target):
106
        """
107
        Args:
108
            target:
109
110
        Returns:
111
            object
112
        """
113
        if isinstance(target, DBRef):
114
            # FIXME: This needs to reference the correct collection
0 ignored issues
show
Coding Style introduced by
TODO and FIXME comments should generally be avoided.
Loading history...
115
            document = self.collection(target.collection).find_one(target.id)
116
            if document:
117
                document = self.hydrate(self.objectify(target.collection, document))
118
            return document
119
        elif isinstance(target, dict):
120
            for key, value in target.items():
121
                if isinstance(value, self.ref_types):
122
                    target[key] = self.hydrate(value)
123
        elif isinstance(target, list):
124
            for i, value in enumerate(target):
125
                if isinstance(value, self.ref_types):
126
                    target[i] = self.hydrate(value)
127
128
        # return target if nothing else occurred
129
        return target
130
131
    def save(self, *args):
132
        """
133
        Args:
134
            *args: One or more documents
135
136
        Returns:
137
138
        """
139
        for document in args:
140
            self.collection(document).save(document)
141
142
    def refresh(self, *args):
143
        """
144
        Args:
145
            *args: One or more documents
146
147
        Returns:
148
149
        """
150
        for document in args:
151
            self.collection(document).refresh(document)
152
153
    def remove(self, *args):
154
        """
155
        Args:
156
            *args: One or more documents
157
        """
158
        for document in args:
159
            self.collection(document).remove(document)
160
161
    def shutdown(self):
162
        """
163
        Returns:
164
165
        """
166
        pass
167