|
| 1 | +import os |
| 2 | +import importlib |
| 3 | +import logging |
| 4 | +from http import HTTPStatus |
| 5 | + |
| 6 | +import requests |
| 7 | +import simplejson |
| 8 | + |
| 9 | +logging.basicConfig(level=logging.DEBUG) |
| 10 | + |
| 11 | +log = logging.getLogger(__name__) |
| 12 | + |
| 13 | +SNIPPETS_DIR = "snippets" |
| 14 | +SORT_KEYS_ON_DUMP = True |
| 15 | +SNIPPET_RESULT_POSTFIX = "_result" |
| 16 | +REMOVE_PYTHON_SNIPPET = True |
| 17 | + |
| 18 | + |
| 19 | +def run_request_for_module(module_name: str): |
| 20 | + log.info("Start processing %r", module_name) |
| 21 | + |
| 22 | + module_full_name = ".".join((SNIPPETS_DIR, module_name)) |
| 23 | + log.debug("import module %s", module_full_name) |
| 24 | + module = importlib.import_module(module_full_name) |
| 25 | + |
| 26 | + log.info("Process module %s", module) |
| 27 | + response: requests.Response = module.response |
| 28 | + log.info("Response %s", response) |
| 29 | + http_response_text = [] |
| 30 | + response_reason = (response.reason or "").title() |
| 31 | + http_response_text.append( |
| 32 | + # "HTTP/1.1 201 Created" |
| 33 | + "{} {} {}".format( |
| 34 | + "HTTP/1.1", |
| 35 | + response.status_code, |
| 36 | + response_reason, |
| 37 | + ) |
| 38 | + ) |
| 39 | + http_response_text.append( |
| 40 | + "{}: {}".format( |
| 41 | + "Content-Type", |
| 42 | + response.headers.get('content-type'), |
| 43 | + ) |
| 44 | + ) |
| 45 | + http_response_text.append("") |
| 46 | + |
| 47 | + http_response_text.append( |
| 48 | + simplejson.dumps( |
| 49 | + response.json(), |
| 50 | + sort_keys=SORT_KEYS_ON_DUMP, |
| 51 | + indent=2, |
| 52 | + ), |
| 53 | + ) |
| 54 | + |
| 55 | + http_response_text.append("") |
| 56 | + |
| 57 | + result_text = "\n".join(http_response_text) |
| 58 | + log.debug("Result text:\n%s", result_text) |
| 59 | + |
| 60 | + result_file_name = "/".join((SNIPPETS_DIR, module_name + SNIPPET_RESULT_POSTFIX)) |
| 61 | + with open(result_file_name, "w") as f: |
| 62 | + res = f.write(result_text) |
| 63 | + log.info("Wrote text (%s) to %r", res, result_file_name) |
| 64 | + |
| 65 | + log.info("Processed %r", module_name) |
| 66 | + |
| 67 | + |
| 68 | +def main(): |
| 69 | + log.warning("Starting") |
| 70 | + |
| 71 | + for module_name in os.listdir(SNIPPETS_DIR): |
| 72 | + if module_name.endswith(".py"): |
| 73 | + try: |
| 74 | + run_request_for_module(module_name[:-3]) |
| 75 | + except Exception: |
| 76 | + log.exception("Could not process module %r, skipping", module_name) |
| 77 | + else: |
| 78 | + if REMOVE_PYTHON_SNIPPET: |
| 79 | + os.unlink("/".join((SNIPPETS_DIR, module_name))) |
| 80 | + |
| 81 | + log.warning("Done") |
| 82 | + |
| 83 | + |
| 84 | +if __name__ == "__main__": |
| 85 | + main() |
0 commit comments