~dkuhlman/python-training-materials/Materials

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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
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
#!/usr/bin/env python

"""
synopsis:
    Serve documents from a document database.
    Use ZeroMQ as a transport layer.
    Support the following API:
    - add -- add a new document.
    - get - retrieve document by ID.
    - search -- retrieve list of (ID, tags, description) for documents
      with the given tags.
    - list -- retrieve a list of all documents
usage:
    The following runs a simple test:
        python doc_database_lib.py <database_file.sqlite>
example:
    python doc_database_lib.py my_database_file.sqlite
"""

import sys
import sqlite3


class DocDatabase(object):
    def __init__(self):
        self.db_name = None
        self.connection = None
        self.cursor = None

    def connect(self, db_name):
        """Create and save a connection to the database (file)."""
        self.db_name = db_name
        self.connection = sqlite3.connect(self.db_name)
        self.cursor = self.connection.cursor()

    def close(self):
        """Close the database connection."""
        self.connection.close()
        self.connection = None
        self.cursor = None

    def commit(self):
        """Commit changes to the database."""
        self.connection.commit()
    flush = commit

    def list(self):
        """Return a list of all the documents in the database.
        Each list item is a list containing: [id, tags, description].
        """
        sql = 'select id, tags,description from documents'
        self.cursor.execute(sql)
        result_block = [
            [id, tags, description] for (id, tags, description) in self.cursor]
        return result_block

    def get(self, id):
        """Retrieve a document by ID and return it."""
        sql = 'select * from documents where id = {}'.format(id)
        self.cursor.execute(sql)
        rows = self.cursor.fetchall()
        if len(rows) < 1:
            result_block = None
        else:
            result_block = rows[0]
        return result_block

    def search(self, tag):
        """Retrieve and return a list of all documents that have a tag.
        Each list item is a list containing: [id, tags, description].
        """
        sql = 'select id, tags, description from documents'
        self.cursor.execute(sql)
        result_block = []
        for (id, tags, description) in self.cursor:
            tag_list = tags.split()
            if tag in tag_list:
                result_block.append([id, tags, description])
        return result_block

    def add(self, tags, description, body):
        """Add a document to the database given its tags, description,
        and body.
        """
        body = body.replace('"', '')
        sql = 'select latest_id from config'
        self.cursor.execute(sql)
        row = self.cursor.fetchall()
        id = row[0][0]
        new_id = id + 1
        self.cursor.execute('update config set latest_id={}'.format(new_id))
        sql = 'insert into documents values ({}, "{}", "{}", "{}")'.format(
            new_id, tags, description, body)
        self.cursor.execute(sql)
        self.connection.commit()
        result = {
            'flag': 'success',
            'id': new_id,
        }
        return result


def usage():
    sys.exit(__doc__)


def main():
    args = sys.argv[1:]
    if len(args) != 1:
        usage()
    db_name = args[0]
    database = DocDatabase()
    database.connect(db_name)
    docs = database.list()
    for doc in docs:
        print 'doc: {}'.format(doc)
    id = docs[0][0]
    doc = database.get(id)
    print '-' * 60
    print 'doc: {}'.format(doc)


if __name__ == '__main__':
    import pdb; pdb.set_trace()
    main()