Test Failed
Pull Request — master (#73)
by macartur
01:46
created

CommonClient   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 29
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 29
rs 10
wmc 5

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __init__() 0 5 2
A make_request() 0 20 3
1
"""REST communication with NApps Server."""
2
# This file is part of kytos-utils.
3
#
4
# Copyright (c) 2016 by Kytos Team.
5
#
6
# Authors:
7
#    Beraldo Leal <beraldo AT ncc DOT unesp DOT br>
8
9
import json
10
import logging
11
import os
12
import sys
13
14
import requests
15
from kytos.utils.config import KytosConfig
16
from kytos.utils.decorators import kytos_auth
17
from kytos.utils.exceptions import KytosException
18
19
log = logging.getLogger(__name__)
20
21
22
class CommonClient:
23
    """Generic class used to make request the Napss server."""
24
25
    def __init__(self, config=None):
26
        """Set Kytos config."""
27
        if config is None:
28
            config = KytosConfig().config
29
        self._config = config
30
31
    @staticmethod
32
    def make_request(endpoint, **kwargs):
33
        """Send a request to server."""
34
        data = kwargs.get('json', [])
35
        package = kwargs.get('package', None)
36
        method = kwargs.get('method', 'GET')
37
38
        function = getattr(requests, method.lower())
39
40
        try:
41
            if package:
42
                response = function(endpoint, data=data,
43
                                    files={'file': package})
44
            else:
45
                response = function(endpoint, json=data)
46
        except requests.exceptions.ConnectionError:
47
            log.error("Couldn't connect to NApps server %s.", endpoint)
48
            sys.exit(1)
49
50
        return response
51
52
53
class NAppsClient(CommonClient):
54
    """Client for the NApps Server."""
55
56
    def get_napps(self):
57
        """Get all NApps from the server."""
58
        endpoint = os.path.join(self._config.get('napps', 'api'), 'napps', '')
59
        res = self.make_request(endpoint)
60
61
        if res.status_code != 200:
62
            msg = 'Error getting NApps from server (%s) - %s'
63
            log.error(msg, res.status_code, res.reason)
64
            sys.exit(1)
65
66
        return json.loads(res.content)['napps']
67
68
    def get_napp(self, username, name):
69
        """Return napp metadata or None if not found."""
70
        endpoint = os.path.join(self._config.get('napps', 'api'), 'napps',
71
                                username, name, '')
72
        res = self.make_request(endpoint)
73
        if res.status_code == 404:  # We need to know if NApp is not found
74
            return None
75
        elif res.status_code != 200:
76
            raise KytosException('Error getting %s/%s from server: (%d) - %s',
77
                                 username, name, res.status_code, res.reason)
78
        return json.loads(res.content)
79
80
    @kytos_auth
81
    def upload_napp(self, metadata, package):
82
        """Upload the napp from the current directory to the napps server."""
83
        endpoint = os.path.join(self._config.get('napps', 'api'), 'napps', '')
84
        metadata['token'] = self._config.get('auth', 'token')
85
        request = self.make_request(endpoint, json=metadata, package=package,
86
                                    method="POST")
87
        if request.status_code != 201:
88
            KytosConfig().clear_token()
89
            log.error("%s: %s", request.status_code, request.reason)
90
            sys.exit(1)
91
92
        # WARNING: this will change in future versions, when 'author' will get
93
        # removed.
94
        username = metadata.get('username', metadata.get('author'))
95
        name = metadata.get('name')
96
97
        print("SUCCESS: NApp {}/{} uploaded.".format(username, name))
98
99
    @kytos_auth
100
    def delete(self, username, napp):
101
        """Delete a NApp.
102
103
        Raises:
104
            requests.HTTPError: If 400 <= status < 600.
105
        """
106
        api = self._config.get('napps', 'api')
107
        endpoint = os.path.join(api, 'napps', username, napp, '')
108
        content = {'token': self._config.get('auth', 'token')}
109
        response = self.make_request(endpoint, json=content, method='DELETE')
110
        response.raise_for_status()
111
112
113
class UsersClient(CommonClient):
114
    """Client for the NApps Server."""
115
116
    def get_users(self):
117
        """Get all Users from the server."""
118
        endpoint = os.path.join(self._config.get('napps', 'api'), 'users', '')
119
        res = self.make_request(endpoint)
120
121
        if res.status_code != 200:
122
            msg = 'Error getting NApps from server (%s) - %s'
123
            log.error(msg, res.status_code, res.reason)
124
            sys.exit(1)
125
126
        return json.loads(res.content)['users']
127
128
    def register(self, user_dict):
129
        """Send a user_dict to Napps server using POST request.
130
131
        Args:
132
            user_dict(dict): Dictionary with user attributes.
133
        Returns:
134
            result(string): Return the response of Napps server.
135
        """
136
        endpoint = os.path.join(self._config.get('napps', 'api'), 'users', '')
137
        res = self.make_request(endpoint, method='POST', json=user_dict)
138
139
        return res.content.decode('utf-8')
140