Created
February 2, 2026 01:19
-
-
Save davidlares/ed6f5ea49604d3aea1a94b19b522cb56 to your computer and use it in GitHub Desktop.
Python's Thread-based HTTP request using callbacks
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
| import threading | |
| import requests | |
| import logging | |
| # logging configuration | |
| logging.basicConfig( | |
| level=logging.DEBUG, | |
| format='%(thread)s %(threadName)s : %(message)s' | |
| ) | |
| def get_pokemon_name(response_json): | |
| name = response_json.get('forms')[0].get('name') | |
| logging.info(f'Pokemon name: {name}') | |
| def error(): | |
| logging.error(f'Unable to perform request') | |
| def generate_request(url, success_callback, error_callback): | |
| response = requests.get(url) | |
| if response.status_code == 200: | |
| # execute callback for success | |
| success_callback(response.json()) # converted to dictionary | |
| else: | |
| # execute callback for errors | |
| error_callback() | |
| if __name__ == "__main__": | |
| thread1 = threading.Thread(target=generate_request, kwargs = {'url': 'https://pokeapi.co/api/v2/pokemon/1/', 'success_callback': get_pokemon_name, 'error_callback': error}) | |
| thread1.start() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment