-
Notifications
You must be signed in to change notification settings - Fork 2
3 http client #8
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 9 commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
ff0fee8
Error test not working
Moasib-Arif efab255
merged into main
Moasib-Arif fe17166
minor chnages
Moasib-Arif 9cc33fd
Working HTTP Client
Moasib-Arif 628194b
Minor changes
Moasib-Arif 2705d52
Added all the imports
Moasib-Arif 6aaad33
updated pycurl
Moasib-Arif 4b3b006
Minor changes
Moasib-Arif 977bd4f
removed import
Moasib-Arif bae9186
Comments addressed
Moasib-Arif bbcee5f
Http client uses requests library
Moasib-Arif 4fe4e83
Made the Requested Changes
Moasib-Arif File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,7 @@ | ||
| { | ||
| "python.testing.pytestArgs": [ | ||
| "tests" | ||
| ], | ||
| "python.testing.unittestEnabled": false, | ||
| "python.testing.pytestEnabled": true | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,5 +0,0 @@ | ||
| from http_clients.http import HttpClient | ||
| from config.config import Config | ||
| from logger.logger import logger | ||
| from slack.slack import SlackNotifier | ||
| from sns.sns import Subscription, publish | ||
This file was deleted.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,69 @@ | ||
| import backoff | ||
| import http.client | ||
| from http.client import HTTPException | ||
| from urllib.parse import urlparse | ||
| import logging | ||
|
|
||
|
|
||
| # Function to log retry attempts | ||
| def log_retry(details): | ||
| logging.error(f"Request failed, retrying... Attempt #{details['tries']}") | ||
|
|
||
|
|
||
| class HttpClient: | ||
| # Initialize HttpClient with a backoff_max value | ||
| def __init__(self, backoff_max=30): | ||
| self.backoff_max = backoff_max | ||
|
|
||
| # GET request method with exponential backoff | ||
| @backoff.on_exception( | ||
| backoff.expo, | ||
| HTTPException, | ||
| max_time=30, | ||
| on_backoff=log_retry | ||
| ) | ||
| def get(self, url, *args, **kwargs): | ||
| timeout = kwargs.pop('timeout', None) | ||
| logging.info(f"Sending GET request to {url}") | ||
| return self._request("GET", url, timeout=timeout, *args, **kwargs) | ||
|
|
||
| # POST request method with exponential backoff | ||
| @backoff.on_exception( | ||
| backoff.expo, | ||
| HTTPException, | ||
| max_time=30, | ||
| on_backoff=log_retry, | ||
| ) | ||
| def post(self, url, *args, **kwargs): | ||
| timeout = kwargs.pop('timeout', None) | ||
| logging.info(f"Sending POST request to {url}") | ||
| return self._request("POST", url, timeout=timeout, *args, **kwargs) | ||
|
|
||
| # Private method to handle the request | ||
| def _request(self, method, url, *args, **kwargs): | ||
| try: | ||
| headers = kwargs.pop('headers', {}) | ||
|
|
||
| url_parts = urlparse(url) | ||
| https_connection = http.client.HTTPSConnection(url_parts.netloc) | ||
| path = url_parts.path or '/' | ||
| https_connection.request(method, path, headers=headers, *args, **kwargs) | ||
|
|
||
| response = https_connection.getresponse() | ||
| response_content = response.read() | ||
| https_connection.close() | ||
|
|
||
| # Raise an exception if the HTTP status is 400 or above | ||
| if response.status >= 400: | ||
| raise HTTPException(f"HTTP request failed with status {response.status}, response: {response_content.decode()}") | ||
|
Moasib-Arif marked this conversation as resolved.
Outdated
|
||
|
|
||
| return response | ||
|
|
||
| # Handle HTTPException separately to log and retry | ||
| except HTTPException as e: | ||
| logging.error(f"Request failed due to {str(e)}, retrying...") | ||
|
Moasib-Arif marked this conversation as resolved.
Outdated
|
||
| raise | ||
| # Handle other exceptions | ||
| except Exception as e: | ||
| logging.error(f"An unexpected error occurred: {str(e)}") | ||
|
Moasib-Arif marked this conversation as resolved.
Outdated
|
||
| raise | ||
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,114 @@ | ||
| import pytest | ||
| from unittest.mock import patch, MagicMock | ||
| from http.client import HTTPResponse, HTTPException | ||
| from dpytools.http_clients.http_custom import HttpClient | ||
|
|
||
| # Mock the HTTPSConnection class | ||
| @patch('http.client.HTTPSConnection') | ||
| def test_get(mock_connection): | ||
| """ | ||
| Test that the get method returns a response object | ||
| """ | ||
|
|
||
| # Create a mock response object | ||
| mock_response = MagicMock(HTTPResponse) | ||
| mock_response.status = 200 | ||
| mock_response.read.return_value = b'Test response content' | ||
| mock_connection.return_value.getresponse.return_value = mock_response | ||
|
|
||
| # Create an instance of HttpClient and make a GET request | ||
| client = HttpClient() | ||
| response = client.get('http://example.com') | ||
|
|
||
| # Assertions to check the response status, content and the connection call | ||
| assert response.status == 200 | ||
| assert response.read().decode() == 'Test response content' | ||
| mock_connection.assert_called_once_with('example.com') | ||
|
|
||
|
|
||
| @patch('http.client.HTTPSConnection') | ||
| def test_post(mock_connection): | ||
| """ | ||
| Test that the post method returns a response object | ||
| """ | ||
|
|
||
| # Create a mock response object | ||
| mock_response = MagicMock(HTTPResponse) | ||
| mock_response.status = 200 | ||
| mock_response.read.return_value = b'Test response content' | ||
| mock_connection.return_value.getresponse.return_value = mock_response | ||
|
|
||
| # Create an instance of HttpClient and make a POST request | ||
| client = HttpClient() | ||
| response = client.post('http://example.com') | ||
|
|
||
| # Assertions to check the response status, content and the connection call | ||
| assert response.status == 200 | ||
| assert response.read().decode() == 'Test response content' | ||
| mock_connection.assert_called_once_with('example.com') | ||
|
|
||
|
|
||
| @patch('http.client.HTTPSConnection') | ||
| def test_backoff_on_exception(mock_connection): | ||
| """ | ||
| Test that the get method retries on HTTPException | ||
| """ | ||
|
|
||
| # Create a mock response object | ||
| mock_response = MagicMock(HTTPResponse) | ||
| mock_response.status = 200 | ||
|
|
||
| # Raise HTTPException on the first call, then return the mock_response | ||
| mock_connection.return_value.getresponse.side_effect = [HTTPException('HTTP Error'), mock_response] | ||
|
Moasib-Arif marked this conversation as resolved.
Outdated
|
||
|
|
||
| # Create an instance of HttpClient and make a GET request | ||
| client = HttpClient() | ||
| response = client.get('http://example.com') | ||
|
|
||
| # Assertions to check the response status and the number of getresponse calls | ||
| assert response.status == 200 | ||
| assert mock_connection.return_value.getresponse.call_count == 2 | ||
|
|
||
|
|
||
| @patch('http.client.HTTPSConnection') | ||
| def test_request(mock_connection): | ||
| """ | ||
| Test that the _request method returns a response object | ||
| """ | ||
|
|
||
| # Create a mock response object | ||
| mock_response = MagicMock(HTTPResponse) | ||
| mock_response.status = 200 | ||
| mock_response.read.return_value = b'Test response content' | ||
| mock_connection.return_value.getresponse.return_value = mock_response | ||
|
|
||
| # Create an instance of HttpClient and make a request | ||
| client = HttpClient() | ||
| response = client._request('GET', 'http://example.com') | ||
|
|
||
| # Assertions to check the response status, content and the connection call | ||
| assert response.status == 200 | ||
| assert response.read().decode() == 'Test response content' | ||
| mock_connection.assert_called_once_with('example.com') | ||
|
|
||
|
|
||
| @patch('http.client.HTTPSConnection') | ||
| def test_request_with_timeout(mock_connection): | ||
| """ | ||
| Test _request method with timeout passed as kwargs | ||
| """ | ||
|
|
||
| # Create a mock response object | ||
| mock_response = MagicMock(HTTPResponse) | ||
| mock_response.status = 200 | ||
| mock_response.read.return_value = b'Test response content' | ||
| mock_connection.return_value.getresponse.return_value = mock_response | ||
|
|
||
| # Create an instance of HttpClient and make a request with a timeout | ||
| client = HttpClient() | ||
| response = client._request('GET', 'http://example.com', timeout=5) | ||
|
|
||
| # Assertions to check the response status, content and the connection call | ||
| assert response.status == 200 | ||
| assert response.read().decode() == 'Test response content' | ||
| mock_connection.assert_called_once_with('example.com') | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.