|
1 | 1 | #!/usr/bin/env python3 |
2 | | -import json |
| 2 | +import logging |
| 3 | +import re |
3 | 4 | import pycountry |
4 | | -from typing import Callable, Dict, Union |
| 5 | +from typing import Dict, Union |
5 | 6 |
|
6 | 7 | import requests |
7 | | -from requests import Response |
| 8 | +from logging import LoggerAdapter |
| 9 | +from requests import Response, PreparedRequest |
8 | 10 | from docassemble.base.functions import all_variables, get_config |
9 | 11 | from docassemble.base.util import ( |
10 | 12 | DAObject, |
|
23 | 25 | __all__ = ["ApiResponse", "ProxyConnection", "state_name_to_code"] |
24 | 26 |
|
25 | 27 |
|
| 28 | +class DALogger(LoggerAdapter): |
| 29 | + def __init__(self, logger): |
| 30 | + super().__init__(logger) |
| 31 | + |
| 32 | + def log(self, level, msg, *args, **kwargs): |
| 33 | + """ |
| 34 | + Delegate a log call to Docassemble's `log` function, after adding |
| 35 | + contextual information from this adapter instance. |
| 36 | + """ |
| 37 | + kwargs |
| 38 | + if not self.isEnabledFor(level): |
| 39 | + return |
| 40 | + |
| 41 | + msg = re.sub(r"\n", " ", msg) |
| 42 | + log(f"[{args}, {kwargs}] {msg}") |
| 43 | + |
| 44 | + |
26 | 45 | def state_name_to_code(state_name: str) -> str: |
27 | 46 | try: |
28 | 47 | return pycountry.subdivisions.lookup(state_name).code.split("-")[-1] |
@@ -147,12 +166,15 @@ def __init__( |
147 | 166 | self.credentials_code_block = credentials_code_block |
148 | 167 |
|
149 | 168 | super().__init__( |
150 | | - url=url, api_key=api_key, default_jurisdiction=default_jurisdiction |
| 169 | + url=url, |
| 170 | + api_key=api_key, |
| 171 | + default_jurisdiction=default_jurisdiction, |
| 172 | + logger=DALogger(logging.getLogger("docassemble")), |
151 | 173 | ) |
152 | 174 |
|
153 | | - def _call_proxy(self, send_func: Callable[[], Response]) -> ApiResponse: |
| 175 | + def _call_proxy(self, req: PreparedRequest) -> ApiResponse: |
154 | 176 | try: |
155 | | - resp = send_func() |
| 177 | + resp = self.proxy_client.send(req) |
156 | 178 | if resp.status_code == 401 and self.credentials_code_block: |
157 | 179 | reconsider(self.credentials_code_block) |
158 | 180 | except requests.ConnectionError as ex: |
|
0 commit comments