request.py 3.44 KB
Newer Older
1
#
Michal Simon's avatar
Michal Simon committed
2
#   See www.eu-emi.eu for details on the copyright holders
3
#
Michal Simon's avatar
Michal Simon committed
4
5
6
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
7
#
Michal Simon's avatar
Michal Simon committed
8
#       http://www.apache.org/licenses/LICENSE-2.0
9
#
Michal Simon's avatar
Michal Simon committed
10
11
12
13
14
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.
15
16
try:
    import simplejson as json
17
18
except:
    import json
19
import logging
20
import requests
21
import tempfile
ayllon's avatar
ayllon committed
22
from exceptions import *
23
import os
24

25
class Request(object):
ayllon's avatar
ayllon committed
26

27
    def __init__(self, ucert, ukey, capath=None, passwd=None, verify=False, access_token=None, connectTimeout=30, timeout=30):
ayllon's avatar
ayllon committed
28
29
        self.ucert = ucert
        self.ukey  = ukey
30
        self.passwd = passwd
31
        self.access_token = access_token
32
33
34
35
36
        self.verify = verify
        # Disable the warnings
        if not verify:
          requests.packages.urllib3.disable_warnings()

37
38
        self.connectTimeout = connectTimeout
        self.timeout = timeout
ayllon's avatar
ayllon committed
39

40
41
        self.session = requests.Session()
        
42

43
44
45
    def _handle_error(self, url, code, response_body=None):
        # Try parsing the response, maybe we can get the error message
        message = None
46
        response = None
47
48
        if response_body:
            try:
49
50
51
52
53
                response = json.loads(response_body)
                if 'message' in response:
                    message = response['message']
                else:
                    message = response_body
54
            except:
55
                message = response_body
56

57
58
59
60
61
62
        if code == 207:
            try:
                raise ClientError('\n'.join(map(lambda m: m['http_message'], response)))
            except (KeyError, TypeError):
                raise ClientError(message)
        elif code == 400:
63
64
65
66
            if message:
                raise ClientError('Bad request: ' + message)
            else:
                raise ClientError('Bad request')
67
        elif 401 <= code <= 403:
68
69
70
71
            if message: 
                raise Unauthorized(message)
            else:
                raise Unauthorized()
72
        elif code == 404:
73
            raise NotFound(url, message)
74
        elif code == 419:
75
            raise NeedDelegation('Need delegation')
76
        elif code == 424:
77
78
            raise FailedDependency('Failed dependency')
        elif 404 < code < 500:
79
            raise ClientError(str(code))
80
81
        elif code == 503:
            raise TryAgain(str(code))
82
83
84
        elif code >= 500:
            raise ServerError(str(code))

85
    def method(self, method, url, body=None, headers=None):   
86
        _headers = {'Accept': 'application/json'}
87
        if headers:
88
89
90
            _headers.update(headers)
        if self.access_token:
            _headers['Authorization'] = 'Bearer ' + self.access_token
91
92
        
        response = self.session.request(method=method, url=str(url), 
93
                             data=body, headers=_headers, verify = self.verify, 
94
95
96
97
98
                             timeout=(self.connectTimeout, self.timeout), 
                             cert=(self.ucert, self.ukey))
        
       
        #log.debug(response.text)
99

100
        self._handle_error(url, response.status_code, response.text)
101

102
        return str(response.text)
103
104


105
__all__ = ['Request']