|
1 | 1 | """Codacy coverage reporter for Python""" |
2 | 2 |
|
3 | 3 | import argparse |
| 4 | +import contextlib |
4 | 5 | import json |
5 | 6 | import logging |
6 | 7 | import os |
7 | 8 | from xml.dom import minidom |
8 | | -import requests |
9 | 9 | from math import floor |
10 | 10 |
|
| 11 | +import requests |
| 12 | +from requests.packages.urllib3 import util as urllib3_util |
| 13 | + |
11 | 14 | logging.basicConfig(level=logging.INFO, |
12 | 15 | format='%(asctime)s - %(levelname)s - %(message)s') |
13 | 16 |
|
14 | 17 | CODACY_PROJECT_TOKEN = os.getenv('CODACY_PROJECT_TOKEN') |
15 | 18 | CODACY_BASE_API_URL = os.getenv('CODACY_API_BASE_URL', 'https://api.codacy.com') |
16 | 19 | URL = CODACY_BASE_API_URL + '/2.0/coverage/{commit}/python' |
17 | 20 | DEFAULT_REPORT_FILE = 'coverage.xml' |
| 21 | +MAX_RETRIES = 3 |
| 22 | +BAD_REQUEST = 400 |
| 23 | + |
| 24 | + |
| 25 | +class _Retry(urllib3_util.Retry): |
| 26 | + |
| 27 | + def is_forced_retry(self, method, status_code): |
| 28 | + return status_code >= BAD_REQUEST |
| 29 | + |
| 30 | + |
| 31 | +@contextlib.contextmanager |
| 32 | +def _request_session(): |
| 33 | + retry = _Retry(total=MAX_RETRIES, raise_on_redirect=False) |
| 34 | + session = requests.Session() |
| 35 | + session.mount("https://", requests.adapters.HTTPAdapter(max_retries=retry)) |
| 36 | + with session: |
| 37 | + yield session |
18 | 38 |
|
19 | 39 |
|
20 | 40 | def get_git_revision_hash(): |
@@ -103,12 +123,14 @@ def upload_report(report, token, commit): |
103 | 123 |
|
104 | 124 | logging.debug(data) |
105 | 125 |
|
106 | | - r = requests.post(url, data=data, headers=headers, allow_redirects=True) |
| 126 | + with _request_session() as session: |
| 127 | + r = session.post(url, data=data, headers=headers, allow_redirects=True) |
107 | 128 |
|
108 | 129 | logging.debug(r.content) |
109 | 130 | r.raise_for_status() |
110 | 131 |
|
111 | 132 | response = json.loads(r.text) |
| 133 | + |
112 | 134 | try: |
113 | 135 | logging.info(response['success']) |
114 | 136 | except KeyError: |
|
0 commit comments