diff --git a/.github/workflows/check.yml b/.github/workflows/check.yml index 1ac4dd2..8071044 100644 --- a/.github/workflows/check.yml +++ b/.github/workflows/check.yml @@ -1,9 +1,22 @@ name: Check examples +# Runs only when code or chapters change: README-only PRs skip it. on: pull_request: + paths: + - "chapters/**" + - "examples/**" + - "scripts/**" + - "*.py" + - ".github/workflows/check.yml" push: branches: [main] + paths: + - "chapters/**" + - "examples/**" + - "scripts/**" + - "*.py" + - ".github/workflows/check.yml" jobs: test: @@ -21,5 +34,7 @@ jobs: run: python3 -c "import json; m = json.load(open('chapters/chapters.json')); import os; [open(os.path.join('chapters', c['file'])) for s in m['sections'] for c in s['chapters']]" - name: Run every example script run: scripts/test_examples.sh + env: + GITHUB_TOKEN: ${{ github.token }} - name: Run every inline snippet in the chapters run: python3 scripts/check_snippets.py diff --git a/chapters/11-json.md b/chapters/11-json.md index 839253e..f693b46 100644 --- a/chapters/11-json.md +++ b/chapters/11-json.md @@ -114,15 +114,23 @@ for line in result.stdout.splitlines(): #!/usr/bin/env python3 # github_stars.py import json +import os import urllib.request url = "https://api.github.com/repos/tuladhar/Python-for-SysAdmin" -with urllib.request.urlopen(url, timeout=10) as response: +request = urllib.request.Request(url) +token = os.environ.get("GITHUB_TOKEN") +if token: # optional: raises the rate limit from 60 to 5,000 requests per hour + request.add_header("Authorization", f"Bearer {token}") + +with urllib.request.urlopen(request, timeout=10) as response: repo = json.load(response) print(f"{repo['full_name']} has {repo['stargazers_count']} stars") ``` +> Without a token, the GitHub API allows only 60 requests per hour per IP address. Shared networks (offices, CI runners) hit that limit quickly and get `HTTP Error 403: rate limit exceeded`. Reading secrets from environment variables, never from the script itself, keeps them out of Git. + ## Exercises - Run `kubectl get pods -A -o json` (or use a saved sample file) and print each pod's namespace, name and phase. diff --git a/examples/github_stars.py b/examples/github_stars.py index a2c7c8e..7247a3d 100644 --- a/examples/github_stars.py +++ b/examples/github_stars.py @@ -1,10 +1,16 @@ #!/usr/bin/env python3 # github_stars.py import json +import os import urllib.request url = "https://api.github.com/repos/tuladhar/Python-for-SysAdmin" -with urllib.request.urlopen(url, timeout=10) as response: +request = urllib.request.Request(url) +token = os.environ.get("GITHUB_TOKEN") +if token: # optional: raises the rate limit from 60 to 5,000 requests per hour + request.add_header("Authorization", f"Bearer {token}") + +with urllib.request.urlopen(request, timeout=10) as response: repo = json.load(response) print(f"{repo['full_name']} has {repo['stargazers_count']} stars")