|
1
|
|
|
#!/usr/bin/env python |
|
2
|
|
|
# SPDX-License-Identifier: LGPL-3.0-only |
|
3
|
1 |
|
|
|
4
|
|
|
"""REST client to request item numbers.""" |
|
5
|
1 |
|
|
|
6
|
|
|
import requests |
|
7
|
1 |
|
|
|
8
|
1 |
|
from doorstop import common, settings |
|
9
|
1 |
|
from doorstop.common import DoorstopError |
|
10
|
1 |
|
from doorstop.server import utilities |
|
11
|
|
|
|
|
12
|
1 |
|
log = common.logger(__name__) |
|
13
|
|
|
|
|
14
|
|
|
|
|
15
|
1 |
|
def exists(path='/documents'): |
|
16
|
|
|
"""Determine if the server exists.""" |
|
17
|
1 |
|
found = False |
|
18
|
1 |
|
url = utilities.build_url(path=path) |
|
19
|
1 |
|
if url: |
|
20
|
1 |
|
log.debug("looking for {}...".format(url)) |
|
21
|
1 |
|
try: |
|
22
|
1 |
|
response = requests.head(url) |
|
23
|
1 |
|
except requests.exceptions.RequestException as exc: |
|
24
|
1 |
|
log.debug(exc) |
|
25
|
|
|
else: |
|
26
|
1 |
|
found = response.status_code == 200 |
|
27
|
1 |
|
if found: |
|
28
|
1 |
|
log.info("found: {}".format(url)) |
|
29
|
1 |
|
return found |
|
30
|
|
|
|
|
31
|
|
|
|
|
32
|
1 |
|
def check(): |
|
33
|
|
|
"""Ensure the server exists.""" |
|
34
|
1 |
|
log.info("checking for a server...") |
|
35
|
1 |
|
if settings.SERVER_HOST is None: |
|
36
|
1 |
|
log.info("no server in use") |
|
37
|
1 |
|
return |
|
38
|
1 |
|
if not settings.SERVER_HOST: |
|
39
|
1 |
|
raise DoorstopError("no server specified") |
|
40
|
1 |
|
if not exists(): |
|
41
|
1 |
|
raise DoorstopError("unknown server: {}".format(settings.SERVER_HOST)) |
|
42
|
|
|
|
|
43
|
|
|
|
|
44
|
1 |
|
def get_next_number(prefix): |
|
45
|
|
|
"""Get the next number for the given document prefix.""" |
|
46
|
1 |
|
number = None |
|
47
|
1 |
|
url = utilities.build_url(path='/documents/{p}/numbers'.format(p=prefix)) |
|
48
|
1 |
|
if not url: |
|
49
|
1 |
|
log.info("no server to get the next number from") |
|
50
|
1 |
|
return None |
|
51
|
1 |
|
headers = {'content-type': 'application/json'} |
|
52
|
1 |
|
response = requests.post(url, headers=headers) |
|
53
|
1 |
|
if response.status_code == 200: |
|
54
|
1 |
|
data = response.json() |
|
55
|
1 |
|
number = data.get('next') |
|
56
|
1 |
|
if number is None: |
|
57
|
1 |
|
raise DoorstopError("bad response from: {}".format(url)) |
|
58
|
1 |
|
log.info("next number from the server: {}".format(number)) |
|
59
|
1 |
|
return number |
|
60
|
|
|
|
|
61
|
|
|
|
|
62
|
|
|
if __name__ == '__main__': |
|
63
|
|
|
import sys |
|
64
|
|
|
|
|
65
|
|
|
if len(sys.argv) != 2: |
|
66
|
|
|
exit("Usage: {} <PREFIX>".format(sys.argv[0])) |
|
67
|
|
|
print(get_next_number(sys.argv[-1])) |
|
68
|
|
|
|