File: api-client.py

package info (click to toggle)
snapd 2.71-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 79,536 kB
  • sloc: ansic: 16,114; sh: 16,105; python: 9,941; makefile: 1,890; exp: 190; awk: 40; xml: 22
file content (40 lines) | stat: -rwxr-xr-x 1,274 bytes parent folder | download | duplicates (10)
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
#!/usr/bin/python3

import argparse
import http.client
import sys
import socket

class UnixSocketHTTPConnection(http.client.HTTPConnection):
    def __init__(self, socket_path):
        super().__init__('localhost')
        self._socket_path = socket_path

    def connect(self):
        s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
        s.connect(self._socket_path)
        self.sock = s


def main(argv):
    parser = argparse.ArgumentParser('Call the snapd REST API')
    parser.add_argument('--socket', default='/run/snapd.socket',
                        help='The socket path to connect to')
    parser.add_argument('--method', default='GET',
                        help='The HTTP method to use')
    parser.add_argument('path', metavar='PATH',
                        help='The HTTP path to request')
    parser.add_argument('body', metavar='BODY', default=None, nargs='?',
                        help='The HTTP request body')
    args = parser.parse_args(argv[1:])

    conn = UnixSocketHTTPConnection(args.socket)
    conn.request(args.method, args.path, args.body)

    response = conn.getresponse()
    body = response.read()
    print(body.decode('UTF-8'))
    return response.status >= 300

if __name__ == '__main__':
    sys.exit(main(sys.argv))