Skip to content
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

Add materials for requests tutorial update #503

Merged
merged 4 commits into from
Feb 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions python-requests/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Python's Requests Library (Guide)

This repository contains code snippets discussed in the associated tutorial on [Python's Requests Library](https://realpython.com/python-requests/).
23 changes: 23 additions & 0 deletions python-requests/custom_token_auth.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import requests
from requests.auth import AuthBase


class TokenAuth(AuthBase):
"""Implements a token authentication scheme."""

def __init__(self, token):
self.token = token

def __call__(self, r):
"""Attach an API token to the Authorization header."""
r.headers["Authorization"] = f"Bearer {self.token}"
return r


if __name__ == "__main__":
token = "<YOUR_GITHUB_PA_TOKEN>"
response = requests.get(
"https://api.github.com/user", auth=TokenAuth(token)
)
print(response.status_code)
print(response.text)
14 changes: 14 additions & 0 deletions python-requests/persist_info_with_session.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import requests

from custom_token_auth import TokenAuth

TOKEN = "<YOUR_GITHUB_PA_TOKEN>"

with requests.Session() as session:
session.auth = TokenAuth(TOKEN)

first_response = session.get("https://api.github.com/user")
second_response = session.get("https://api.github.com/user")

print(first_response.headers)
print(second_response.json())
15 changes: 15 additions & 0 deletions python-requests/raise_error.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import requests
from requests.exceptions import HTTPError

URLS = ["https://api.github.com", "https://api.github.com/invalid"]

for url in URLS:
try:
response = requests.get(url)
response.raise_for_status()
except HTTPError as http_err:
print(f"HTTP error occurred: {http_err}")
except Exception as err:
print(f"Other error occurred: {err}")
else:
print("Success!")
5 changes: 5 additions & 0 deletions python-requests/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
certifi==2024.2.2
charset-normalizer==3.3.2
idna==3.6
requests==2.31.0
urllib3==2.2.1
26 changes: 26 additions & 0 deletions python-requests/retry_thrice.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import logging

import requests
from requests.adapters import HTTPAdapter
from requests.exceptions import RetryError
from urllib3.util import Retry

logging.basicConfig(level=logging.DEBUG)

retries = Retry(total=3, status_forcelist=[404])

github_adapter = HTTPAdapter(max_retries=retries)

session = requests.Session()

session.mount("https://api.github.com", github_adapter)

try:
response = session.get("https://api.github.com/")
print(response.status_code)
response = session.get("https://api.github.com/invalid")
print(response.status_code)
except RetryError as err:
print(f"Error: {err}")
finally:
session.close()
16 changes: 16 additions & 0 deletions python-requests/retry_twice.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import requests
from requests.adapters import HTTPAdapter
from requests.exceptions import RetryError

github_adapter = HTTPAdapter(max_retries=2)

session = requests.Session()

session.mount("https://api.github.com", github_adapter)

try:
response = session.get("https://api.github.com/")
except RetryError as err:
print(f"Error: {err}")
finally:
session.close()
16 changes: 16 additions & 0 deletions python-requests/search_popular_repos.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import requests

# Search GitHub's repositories for popular Python projects
response = requests.get(
"https://api.github.com/search/repositories",
params={"q": "language:python", "sort": "stars", "order": "desc"},
)

# Inspect some attributes of the first three repositories
json_response = response.json()
popular_repositories = json_response["items"]
for repo in popular_repositories[:3]:
print(f"Name: {repo['name']}")
print(f"Description: {repo['description']}")
print(f"Stars: {repo['stargazers_count']}")
print()
13 changes: 13 additions & 0 deletions python-requests/text_matches.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import requests

response = requests.get(
"https://api.github.com/search/repositories",
params={"q": '"real python"'},
headers={"Accept": "application/vnd.github.text-match+json"},
)

# View the new `text-matches` list which provides information
# about your search term within the results.
json_response = response.json()
first_repository = json_response["items"][0]
print(first_repository["text_matches"][0]["matches"])
9 changes: 9 additions & 0 deletions python-requests/timeout_catcher.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import requests
from requests.exceptions import Timeout

try:
response = requests.get("https://api.github.com", timeout=(3.05, 5))
except Timeout:
print("The request timed out")
else:
print("The request did not time out")
Loading