~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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
#!/usr/bin/env python

"""
synopsis:
    Client that requests document services.
    Use ZeroMQ as a transport layer.
    Request the following services:
    - add document.
    - list all documents in the database.
    - get document by ID.
    - search for documents with a given tag.
usage:
    python zmq_doc_client01.py [options] command arg1 arg2 ...
options:
    None
examples:
    python zmq_doc_client01.py add "tag tag" "description" <filename>
    python zmq_doc_client01.py list
    python zmq_doc_client01.py get <id>
    python zmq_doc_client01.py search <tag>
"""

import sys
import getopt
from cmd import Cmd
import zmq_doc_client01 as doc_client


class DocServeCmdLine(Cmd):
    def __init__(self):
        Cmd.__init__(self)
        self.prompt = 'Enter cmd: '

    do_h = Cmd.do_help

    def do_list(self, args):
        """Retrieve and show a list of all documents.  Show ids, tags,
            and descriptions.
        usage: list
        """
        docs = doc_client.list_request([], show=False)
        for doc in docs:
            print 'document:'
            print '    id:          {}'.format(doc[0])
            print '    tags:        {}'.format(doc[1])
            print '    description: {}'.format(doc[2])
        return False

    def do_get(self, args):
        """Retrieve a single document by ID.  Show the document ID, tags,
            description, and body.
        usage: get <id>
        """
        args = args.split()
        if len(args) != 1:
            return False
        id = int(args[0])
        doc = doc_client.get_request([id], show=False)
        if doc is None:
            print 'document {} not found'.format(id)
        else:
            print 'document:'
            print '    id:          {}'.format(doc['id'])
            print '    tags:        {}'.format(doc['tags'])
            print '    description: {}'.format(doc['description'])
            print '    body:        {}'.format(doc['body'])
        return False

    def do_search(self, args):
        """Search for a set of documents by tag.
        usage: search <tag>
        """
        args = args.split()
        if len(args) != 1:
            return False
        tag = args[0]
        docs = doc_client.search_request([tag], show=False)
        for doc in docs:
            print 'document:'
            print '    id:          {}'.format(doc[0])
            print '    tags:        {}'.format(doc[1])
            print '    description: {}'.format(doc[2])
        return False

    def do_add(self, args):
        """Add a new document to the repository.
        usage: add <tags>::<description>::<filename>
        """
        args = args.split('::')
        if len(args) != 3:
            return False
        tags = args[0]
        description = args[1]
        filename = args[2]
        message = None
        args = [tags, description, filename]
        try:
            print '(cmd) sending request: "{}"'.format(args)
            message = doc_client.add_request(args, show=False)
        except IOError:
            print "can't read file: {}".format(filename)
        if message is not None:
            print 'message: {}'.format(message)
        return False

    def emptyline(self):
        pass

    def do_quit(self, args):
        """Say goodbye and quit.
        """
        print 'bye'
        # Return True in order to exit from the command loop.
        return True
    do_exit = do_quit


def start():
    """Start up the command line client.
    """
    cmdline = DocServeCmdLine()
    cmdline.cmdloop('Welcome to the doc server.')


def usage():
    sys.exit(__doc__)


def main():
    args = sys.argv[1:]
    try:
        opts, args = getopt.getopt(args, 'h', ['help', ])
    except:
        usage()
    for opt, val in opts:
        if opt in ('-h', '--help'):
            usage()
    if len(args) != 0:
        usage()
    start()


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