代码如下:
import json import requests from requests import exceptions URL = 'https://api.github.com' def build_uri(endpoint): return '/'.join([URL,endpoint]) def better_print(json_str): #打印出来更好看 return json.dumps(json.loads(json_str),indent=4) #缩进为4def timeout_request(): try: response = requests.get(build_uri('user/emails'),timeout=10) response.raise_for_status() #状态不是200会抛异常 except exceptions.Timeout as e: #超时异常 print(e) except exceptions.HTTPError as e: print(e) else: print(better_print(response.text)) #没问题时打印出来response内容 print(response.status_code) if __name__ == '__main__': timeout_request()
完