Request
- Make a simple request
import requests
url = 'http://api.openweathermap.org/data/2.5/weather'
payload = {'q': 'shanghai', 'units': 'metric', 'lang': 'zh_cn', 'appid': <appid>}
r = requests.get(url, params=payload)
- Get JSON response data
data = r.json()
- Response Status Code
if r.status_code == 200:
data = r.json()
Or use the built-in status code for easy reference
if r.status_code == requests.codes.ok:
data = r.json()
- Timeout
To stop waiting for a response after a given number of seconds with the timeout parameter
r = requests.get(api, params=payload, timeout=0.001)
If no timeout parameters, the program may hang indefinitely.
- Exception
In the event of a network problem (e.g. DNS failure, refused connection, etc), Requests will raise a ConnectionError exception.
If a request times out, a Timeout exception is raised.
try:
r = requests.get(url, params=params, timeout=0.001)
if r.status_code == requests.codes.ok:
data = r.json()
else:
print('Bad Request!')
except (requests.Timeout, requests.ConnectionError):
print('Network problem or request timeout!')