Skip to content

Database

initialize_db(app)

The initialize_db function is called by the application factory. It initializes our database and sets up a custom JSON encoder for our models.

Parameters:

Name Type Description Default
app

Access the application instance itself, and is used to get access to the

required

Returns:

Type Description

A flask application object

Source code in database/db.py
14
15
16
17
18
19
20
21
22
23
24
25
26
27
def initialize_db(app):
    """
    The initialize_db function is called by the application factory.
    It initializes our database and sets up a custom JSON encoder for our models.

    Args:
        app: Access the application instance itself, and is used to get access to the

    Returns:
        A flask application object
    """

    db.init_app(app)
    app.session_interface = MongoEngineSessionInterface(db)

Collection

Bases: db.Document

This class is a MongoDB document that represents a collection of items

Source code in database/models.py
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
class Collection(db.Document):
    """This class is a MongoDB document that represents a collection of items"""

    meta = {"collection": "collection"}

    name = db.StringField(required=True, unique=False)
    owner = db.ReferenceField("User", required=True)
    snippets = db.ListField(db.ReferenceField("Snippet", reverse_delete_rule=db.PULL))
    private = db.BooleanField(default=False)
    date = db.DateTimeField(default=datetime.datetime.utcnow)

    def __repr__(self):
        return self.name

    def __str__(self):
        return self.name

Snippet

Bases: db.Document

The Snippet class inherits from the db.Document class, which is a MongoEngine class that allows us to save documents to MongoDB

Source code in database/models.py
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
class Snippet(db.Document):
    """The `Snippet` class inherits from the `db.Document` class, which is a MongoEngine class that allows us to save
    documents to MongoDB"""

    meta = {
        "collection": "snippet",
    }

    title = db.StringField(required=True, unique=False)
    filename = db.StringField(unique=False)
    tags = db.ListField(db.StringField())
    description = db.StringField()
    language = db.StringField(default="javascript")
    value = db.StringField(required=True)
    addedBy = db.ReferenceField("User", required=True)
    likedBy = db.ListField(db.ReferenceField("User"))
    addedOn = db.DateTimeField(required=True, default=datetime.datetime.utcnow)
    updatedOn = db.DateTimeField()
    private = db.BooleanField(default=False)
    active: db.BooleanField(default=True)
    source = db.URLField(unique=False)
    score = db.IntField(required=True, default=0)

    def like_count(self):
        """
        The like_count function returns the number of likes that a post has.
        It takes in self as an argument, which is the instance of Post that called it.

        Args:
            self: Refer to the object that is calling the method

        Returns:
            The length of the likedby list

        Doc Author:
            Trelent
        """
        return len(self.likedBy)

    def __repr__(self):
        """
        The __repr__ function is what tells Python how to represent an object of our class as a string.
        The default implementation for this function is to return the instance address, which in this case would be:
        <__main__.Post object at 0x7f8c9d6b0a90>

        Args:
            self: Refer to the object that is calling the function

        Returns:
            The title of the object

        Doc Author:
            Trelent
        """
        return self.title

    def __str__(self):
        return self.title

__repr__()

The repr function is what tells Python how to represent an object of our class as a string. The default implementation for this function is to return the instance address, which in this case would be: <main.Post object at 0x7f8c9d6b0a90>

Parameters:

Name Type Description Default
self

Refer to the object that is calling the function

required

Returns:

Type Description

The title of the object

Doc Author

Trelent

Source code in database/models.py
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
def __repr__(self):
    """
    The __repr__ function is what tells Python how to represent an object of our class as a string.
    The default implementation for this function is to return the instance address, which in this case would be:
    &lt;__main__.Post object at 0x7f8c9d6b0a90&gt;

    Args:
        self: Refer to the object that is calling the function

    Returns:
        The title of the object

    Doc Author:
        Trelent
    """
    return self.title

like_count()

The like_count function returns the number of likes that a post has. It takes in self as an argument, which is the instance of Post that called it.

Parameters:

Name Type Description Default
self

Refer to the object that is calling the method

required

Returns:

Type Description

The length of the likedby list

Doc Author

Trelent

Source code in database/models.py
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
def like_count(self):
    """
    The like_count function returns the number of likes that a post has.
    It takes in self as an argument, which is the instance of Post that called it.

    Args:
        self: Refer to the object that is calling the method

    Returns:
        The length of the likedby list

    Doc Author:
        Trelent
    """
    return len(self.likedBy)

User

Bases: db.Document

The User class is a subclass of the db.Document class, which is a subclass of the db.Model class

Source code in database/models.py
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
class User(db.Document):
    """The User class is a subclass of the db.Document class, which is a subclass of the db.Model class"""

    meta = {"collection": "user"}
    username = db.StringField(required=True, unique=True)
    email = db.EmailField(required=True, unique=True)
    password = db.StringField(required=True, min_length=6)
    online = db.BooleanField(default=True)
    snippets_created = db.ListField(
        db.ReferenceField("Snippet", reverse_delete_rule=db.PULL)
    )
    snippets_liked = db.ListField(
        db.ReferenceField("Snippet", reverse_delete_rule=db.PULL)
    )
    collections = db.ListField(db.ReferenceField("Collection"))

    def hash_password(self):
        self.password = generate_password_hash(self.password).decode("utf8")

    def check_password(self, password):
        """
        The check_password function takes in a password and the hash of the password
        and checks if they are equal. If they are, it returns true. Otherwise, it returns false.

        Args:
            self: Reference the instance of the object that is being created
            password: Check the password entered by the user against the hashed password stored in the database

        Returns:
            True or false depending on whether the password_hash matches the password

        """
        return check_password_hash(self.password, password)

    def __repr__(self):
        return 'User(email="{}", username="{}")'.format(self.username, self.password)

    def __str__(self):
        return self.username

check_password(password)

The check_password function takes in a password and the hash of the password and checks if they are equal. If they are, it returns true. Otherwise, it returns false.

Parameters:

Name Type Description Default
self

Reference the instance of the object that is being created

required
password

Check the password entered by the user against the hashed password stored in the database

required

Returns:

Type Description

True or false depending on whether the password_hash matches the password

Source code in database/models.py
112
113
114
115
116
117
118
119
120
121
122
123
124
125
def check_password(self, password):
    """
    The check_password function takes in a password and the hash of the password
    and checks if they are equal. If they are, it returns true. Otherwise, it returns false.

    Args:
        self: Reference the instance of the object that is being created
        password: Check the password entered by the user against the hashed password stored in the database

    Returns:
        True or false depending on whether the password_hash matches the password

    """
    return check_password_hash(self.password, password)

all_languages()

The all_languages function returns a list of all the languages that have been used in any snippet. It does this by querying the Snippet collection and then iterating through each document to check if the language field is already in the list of all_languages. If it isn't, it adds it to the list.

Returns:

Type Description

A list of all the languages in the database

Source code in database/constants.py
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
def all_languages():
    """
    The all_languages function returns a list of all the languages that have been used in any snippet.
    It does this by querying the Snippet collection and then iterating through each document to check if
    the language field is already in the list of all_languages. If it isn't, it adds it to the list.

    Returns:
        A list of all the languages in the database
    """

    all_languages = []
    all_snippets = Snippet.objects()
    for doc in all_snippets:
        if doc["language"] not in all_languages:
            all_languages.append(doc["language"])
    return all_languages

all_tags()

The all_tags function returns a list of all the tags in the database. It does this by iterating through each snippet and appending any new tag to the list of all_tags. It then returns that list.

Returns:

Type Description

A list of all the tags in the database

Source code in database/constants.py
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
def all_tags():
    """
    The all_tags function returns a list of all the tags in the database.
    It does this by iterating through each snippet and appending any new tag to
    the list of all_tags. It then returns that list.

    Returns:
        A list of all the tags in the database
    """

    all_tags = []
    all_snippets = Snippet.objects()
    for tag in Snippet.objects():
        for k in tag["tags"]:
            if k not in all_tags:
                all_tags.append(k)
    return all_tags