Implement debug logging

This commit is contained in:
agatha 2023-09-08 21:29:06 -04:00
parent 512290d2cf
commit 5578fcc43e
3 changed files with 26 additions and 18 deletions

View File

@ -22,3 +22,7 @@ The ApiWrapper class defines custom exceptions for handling API request and resp
- `InvalidApiResponse` is raised when the API response is not a valid JSON.
You can catch these exceptions and handle them accordingly in your code.
## Debugging
To turn on debugging, initialize the wrapper with `debug=True`. This will set the log level of
`urllib3` to `logging.DEBUG`

View File

@ -1,4 +1,4 @@
from wrapper import ApiWrapper
import wrapper
def main():
@ -6,24 +6,16 @@ def main():
ApiWrapper example.
"""
# Initialize ApiWrapper
api = ApiWrapper('https://jsonplaceholder.typicode.com')
api = wrapper.ApiWrapper('https://jsonplaceholder.typicode.com', debug=True)
# Test get_users method
users = api.get_users()
for user in users:
print(user)
# Reinitialize ApiWrapper with broken proxy
# This should raise an InvalidRequestException
api = ApiWrapper(
'https://jsonplaceholder.typicode.com',
proxies={'http': 'http://localhost:23451', 'https': 'http://localhost:23451'}
)
# Test broken proxy
users = api.get_users()
for user in users:
print(user)
try:
users = api.get_users()
except wrapper.ApiRequestException as e:
print(str(e))
else:
for user in users:
print(user)
if __name__ == '__main__':

View File

@ -6,11 +6,15 @@ endpoints of the API using HTTP requests. It supports custom headers and proxies
additional flexibility.
"""
import json
import logging
import requests
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry
logger = logging.getLogger()
class InvalidApiResponse(Exception):
pass
@ -31,13 +35,14 @@ class ApiWrapper:
base_url (str): The base URL of the API.
headers (dict, optional): Dictionary containing customer headers to be sent with each request.
proxies (dict, optional): Dictionary containing proxy settings to be used for requests.
debug (bool, optional): Setting this to true will print `urllib3` debug information.
Attributes:
base_url (str): The base URL of the API.
session (requests.Session): Persistent HTTP session.
"""
def __init__(self, base_url, headers=None, proxies=None):
def __init__(self, base_url, headers=None, proxies=None, debug=False):
self.base_url = base_url
self.session = requests.Session()
@ -50,6 +55,13 @@ class ApiWrapper:
if proxies:
self.session.proxies.update(proxies)
if debug:
if not logger.handlers:
logging.basicConfig()
logging.getLogger("urllib3").setLevel(logging.DEBUG)
def __get(self, endpoint, params=None):
url = self.base_url + endpoint