#!/usr/bin/env python3 """Python 3 standard library example. Set XZ_API_SECRET_ID and XZ_API_SECRET_KEY in the server environment.""" import argparse import hashlib import hmac import json import os import secrets import time import urllib.error import urllib.parse import urllib.request def get_photos(photographer_id, page=1, limit=10, sort="latest"): if not 1 <= photographer_id <= 2147483647: raise ValueError("Invalid photographer ID") if not 1 <= page <= 100000 or not 1 <= limit <= 20 or sort not in ("latest", "popular"): raise ValueError("Invalid pagination or sort") params = {"page": str(page), "limit": str(limit), "sort": sort} timestamp, nonce = str(int(time.time())), secrets.token_hex(16) signed = dict(params, timestamp=timestamp, nonce=nonce) canonical = "&".join(f"{key}={signed[key]}" for key in sorted(signed)) signature = hmac.new(os.environ["XZ_API_SECRET_KEY"].encode(), canonical.encode(), hashlib.sha256).hexdigest() url = f"https://api.xzphotos.cn/api/v1/photographers/{photographer_id}/photos?{urllib.parse.urlencode(params)}" request = urllib.request.Request(url, headers={ "X-SECRET-ID": os.environ["XZ_API_SECRET_ID"], "X-TIMESTAMP": timestamp, "X-NONCE": nonce, "X-SIGNATURE": signature, "Accept": "application/json", "User-Agent": "XZPhotos-Partner-Example/1.0", }) # No automatic retries: a repeated successful request can incur a second charge. try: with urllib.request.urlopen(request, timeout=20) as response: return response.status, dict(response.headers), json.load(response) except urllib.error.HTTPError as error: return error.code, dict(error.headers), json.load(error) if __name__ == "__main__": parser = argparse.ArgumentParser(description="Fetch one page of a photographer's public photographs") parser.add_argument("photographer_id", type=int) parser.add_argument("--page", type=int, default=1) parser.add_argument("--limit", type=int, default=10) parser.add_argument("--sort", choices=["latest", "popular"], default="latest") args = parser.parse_args() status, headers, body = get_photos(args.photographer_id, args.page, args.limit, args.sort) print("HTTP", status) for name, value in headers.items(): if name.lower() in ("x-request-cost", "x-account-balance"): print(name + ":", value) print(json.dumps(body, ensure_ascii=False, indent=2))