【Python】requestsマスター〜リトライ〜通信の例外処理まで

##導入
```
pip install requests
```

##インポート
```Python
import requests
```

##簡易な実行
```Python
import requests

# GET
requests.get('https://xxx')
# POST
requests.post('https://xxx')
```

##実践に近い実行
###GET
```Python
import requests
import json

header = {'content-type': "Application/json"}

parameter = {
        'key0': 'value0',
        'key1': 'value1'
    }

response = requests.get(url="https://xxx",
                        headers=header,
                        params=parameter)

print(response.status_code)
print(response.json())
```

###POST
```Python
import requests
import json

header = {'content-type': "Application/json"}

values = {
        'key0': 'value0',
        'key1': 'value1'
    }

response = requests.post(url="https://xxx",
                         headers=header,
                         data=json.dumps(values))

print(response.status_code)
print(response.json())
```

##Session貼ってRetryも設定しちゃう気合の入った実行
###GET
```Python
import requests
from urllib3.util import Retry
from requests.adapters import HTTPAdapter
import json

header = {'content-type': "Application/json"}

parameter = {
        'key0': 'value0',
        'key1': 'value1'
    }

session = requests.Session()

retries = Retry(total=5,  # リトライ回数
                backoff_factor=1,  # sleep時間
                status_forcelist=[500, 502, 503, 504])  # timeout以外でリトライするステータスコード

session.mount("https://", HTTPAdapter(max_retries=retries))

# connect timeoutを10秒, read timeoutを30秒に設定
response = session.get(url="https://xxx",
                       headers=header,
                       params=parameter,
                       stream=True,
                       timeout=(10.0, 30.0))

print(response.status_code)
print(response.json())
```

###POST
```Python
import requests
from urllib3.util import Retry
from requests.adapters import HTTPAdapter
import json

header = {'content-type': "Application/json"}

values = {
        'key0': 'value0',
        'key1': 'value1'
    }

session = requests.Session()

retries = Retry(total=5,  # リトライ回数
                backoff_factor=1,  # sleep時間
                status_forcelist=[500, 502, 503, 504])  # timeout以外でリトライするステータスコード

session.mount("https://", HTTPAdapter(max_retries=retries))

# connect timeoutを10秒, read timeoutを30秒に設定
response = session.post(url="https://xxx",
                       headers=header,
                       data=json.dumps(values),
                       stream=True,
                       timeout=(10.0, 30.0))

print(response.status_code)
print(response.json())
```

##TimeOutで例外が投げられるのでtry-except

###GET
```Python
import requests
from urllib3.util import Retry
from requests.adapters import HTTPAdapter
import json

header = {'content-type': "Application/json"}

values = {
        'key0': 'value0',
        'key1': 'value1'
    }

session = requests.Session()

retries = Retry(total=5,  # リトライ回数
                backoff_factor=1,  # sleep時間
                status_forcelist=[500, 502, 503, 504])  # timeout以外でリトライするステータスコード

session.mount("https://", HTTPAdapter(max_retries=retries))

try:
    # connect timeoutを10秒, read timeoutを30秒に設定
    response = session.get(url="https://xxx",
                           headers=header,
                           params=parameter,
                           stream=True,
                           timeout=(10.0, 30.0))

except requests.exceptions.ConnectTimeout:
    print('タイムアウトしました')
    sys.exit()
else:
    print(response.status_code)
    print(response.json())
```

###POST
```Python
import requests
from urllib3.util import Retry
from requests.adapters import HTTPAdapter
import json

header = {'content-type': "Application/json"}

values = {
        'key0': 'value0',
        'key1': 'value1'
    }

session = requests.Session()

retries = Retry(total=5,  # リトライ回数
                backoff_factor=1,  # sleep時間
                status_forcelist=[500, 502, 503, 504])  # timeout以外でリトライするステータスコード

session.mount("https://", HTTPAdapter(max_retries=retries))

try:
    # connect timeoutを10秒, read timeoutを30秒に設定
    response = session.post(url="https://xxx",
                           headers=header,
                           data=json.dumps(values),
                           timeout=(10.0, 30.0))

except requests.exceptions.ConnectTimeout:
    print('タイムアウトしました')
    sys.exit()
else:
    print(response.status_code)
    print(response.json())
```

###備考
Pythonではtry句、else句、あとfinally句のスコープは同じなようです。（最初まじかよと思った）

#参考
[Requests: HTTP for Humans](https://2.python-requests.org//en/master/#) 
[pythonのrequestsでリトライとプロキシを設定](http://blog.mwsoft.jp/article/175043478.html)