53
47

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

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

Posted at

##導入

pip install requests

##インポート

import requests

##簡易な実行

import requests

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

##実践に近い実行
###GET

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

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

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

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

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

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
pythonのrequestsでリトライとプロキシを設定

53
47
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
53
47

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?