Last active
February 25, 2025 20:34
-
-
Save petergs/f62c5ba2f3e14fffd306f203bc2cb02a to your computer and use it in GitHub Desktop.
urllib.request example
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 urllib.request | |
| import urllib.parse | |
| import urllib.error | |
| def urlreq(method: str, url: str, headers: dict = {}, data: dict | None = None) -> str: | |
| encoded_data = None | |
| if data is not None: | |
| if method == "GET": | |
| # urlencode data as path parameters | |
| params = "&".join( | |
| "{}={}".format(k, urllib.parse.quote_plus(v)) for k, v in data.items() | |
| ) | |
| url = f"{url}?{params}" | |
| else: | |
| if headers.get("Content-Type") == "application/x-www-form-urlencoded": | |
| encoded_data: bytes | None = urllib.parse.urlencode(data).encode() | |
| else: | |
| encoded_data: bytes | None = json.dumps(data).encode("utf-8") | |
| request = urllib.request.Request( | |
| url=url, data=encoded_data, headers=headers, method=method | |
| ) | |
| with urllib.request.urlopen(request) as response: | |
| return response.read().decode("utf-8") | |
| if __name__ == "__main__": | |
| try: | |
| urlreq(method="GET", url="https://jsonplaceholder.typicode.com/posts") | |
| except urllib.error.HTTPError as e: | |
| print(f"The server couldn't fulfill the request. \n Error code: {e.code}") | |
| except urllib.error.URLError as e: | |
| print(f"We failed to reach a server. \n Reason: {e.reason}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment