Passed
Push — feature/variant_op ( 29d94f...8855ef )
by srz
27:08 queued 21:07
created

wandbox.Wandbox.timeout()   A

Complexity

Conditions 1

Size

Total Lines 3
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
nop 2
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
#!/usr/bin/env python
2
#
3
# wandbox.py
4
#
5
6
"""
7
Wandbox API for Python
8
"""
9
10
import requests
11
import json
12
13
from time import sleep
14
from requests.exceptions import HTTPError as RHTTPError
15
from requests.exceptions import ConnectionError as RConnectionError
16
from requests.exceptions import ConnectTimeout as RConnectTimeout
17
18
#
19
#
20
class Wandbox:
21
    """wandbox api class"""
22
23
    #api_url = 'http://melpon.org/wandbox/api'
24
    api_url = 'https://wandbox.org/api'
25
    timeout_ = (3.0, 60.0 * 5)
26
27
    def __init__(self):
28
        self.reset()
29
30
    def __enter__(self):
31
        return self
32
33
    def __exit__(self, exc_type, exc_value, traceback):
34
        self.reset()
35
        return False
36
37
    @staticmethod
38
    def GetCompilerList():
39
        """
40
        get compiler list
41
        """
42
        response = requests.get(Wandbox.api_url + '/list.json', timeout=3.0)
43
        response.raise_for_status()
44
        return response.json()
45
46
    def get_compiler_list(self):
47
        """
48
        get compiler list
49
        .. deprecated:: 0.3.4
50
        """
51
        return Wandbox.GetCompilerList()
52
53
    @staticmethod
54
    def GetPermlink(link):
55
        """
56
        get wandbox permanet link
57
        """
58
        response = requests.get(Wandbox.api_url + '/permlink/' + link, timeout=3.0)
59
        response.raise_for_status()
60
        return response.json()
61
62
    @property
63
    def timeout(self):
64
        return self.timeout_
65
66
    @timeout.setter
67
    def timeout(self, v):
68
        self.timeout_ = v
69
70
    def get_permlink(self, link):
71
        """
72
        get wandbox permanet link
73
        .. deprecated:: 0.3.4
74
        """
75
        return Wandbox.GetPermlink(link)
76
77
    def run(self):
78
        """
79
        excute on wandbox
80
        """
81
        headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
82
        payload = json.dumps(self.parameter)
83
        response = requests.post(self.api_url + '/compile.json', data=payload, headers=headers, timeout=self.timeout_)
84
        response.raise_for_status()
85
        try:
86
            return response.json()
87
        except json.decoder.JSONDecodeError as e:
88
            raise requests.exceptions.HTTPError(e, response.status_code)
89
90
    def code(self, code):
91
        """
92
        set main source code
93
        """
94
        self.parameter.update({'code': code})
95
96
    def add_file(self, filename, code):
97
        """
98
        append file
99
        """
100
        if 'codes' in self.parameter:
101
            self.parameter['codes'].append({'file': filename, 'code': code})
102
        else:
103
            self.parameter.update({'codes': [{'file': filename, 'code': code}]})
104
105
    def compiler(self, name):
106
        """
107
        set compiler name
108
        """
109
        self.parameter.update({'compiler': name})
110
111
    def options(self, options_str):
112
        """
113
        set wandbox options
114
        """
115
        self.parameter.update({'options': options_str})
116
117
    def stdin(self, input_str):
118
        """
119
        set stdin buffer
120
        """
121
        self.parameter.update({'stdin': input_str})
122
123
    def compiler_options(self, options_str):
124
        """
125
        set wandbox defined compiler options
126
        """
127
        self.parameter.update({'compiler-option-raw': options_str})
128
129
    def add_compiler_options(self, options_str):
130
        """
131
        set compiler options
132
        """
133
        if 'compiler-option-raw' not in self.parameter:
134
            self.compiler_options(options_str)
135
        else:
136
            option = self.parameter['compiler-option-raw']
137
            option += '\n'
138
            option += options_str
139
            self.parameter.update({'compiler-option-raw': option})
140
141
    def runtime_options(self, options_str):
142
        """
143
        set runtime options
144
        """
145
        self.parameter.update({'runtime-option-raw': options_str})
146
147
    def permanent_link(self, enable):
148
        """
149
        wandbox permanet link to enable
150
        """
151
        self.parameter.update({'save': enable})
152
153
    def dump(self):
154
        """
155
        dump parameters
156
        """
157
        print(self.parameter)
158
159
    def reset(self):
160
        """
161
        reset parametes
162
        """
163
        self.parameter = {'code': ''}
164
165
    @staticmethod
166
    def Call(action, retries, retry_wait):
167
        try:
168
            return action()
169
        except (RHTTPError, RConnectionError, RConnectTimeout) as e:
170
171
            def is_retry(e):
172
                if e is None:
173
                    return False
174
                if e.response is None:
175
                    return False
176
                return e.response.status_code in [500, 502, 503, 504]
177
178
            retries -= 1
179
            if is_retry(e) and retries > 0:
180
                try:
181
                    print(e.message)
182
                except:
183
                    pass
184
                print('wait {0}sec...'.format(retry_wait))
185
                sleep(retry_wait)
186
                return Wandbox.Call(action, retries, retry_wait)
187
            else:
188
                raise
189
        except:
190
            raise
191
192
193
if __name__ == '__main__':
194
    with Wandbox() as w:
195
        w.compiler('gcc-head')
196
        w.options('warning,gnu++1y')
197
        w.compiler_options('-Dx=hogefuga\n-O3')
198
        w.code('#include <iostream>\nint main() { int x = 0; std::cout << "hoge" << std::endl; }')
199
        print(w.run())
200