LoginSignup
0
0

pythonのrequestsライブラリで、x-www-form-urlencodedでpost送信し、タイムアウト時間を設定してみた

Posted at

やりたいこと

pythonのrequestsライブラリでpostリクエストを投げたいけど、システムの制限でタイムアウトエラーで処理結果をコントロールしたい

前提

・Pythonインストール済み
・requestsライブラリインストール済み
・urllibライブラリインストール済み

やり方

今回の要件は以下となります

x-www-form-urlencoded形式でpostリクエストを送信する

 ⇒headersパラメータにContent-Typeを設定すべき

connect timeout(相手のサーバーと接続を確立するまでの待ち時間)を3秒、read timeout(接続確立後、相手のサーバーからレスポンスが帰ってくるまでの待ち時間)を5秒にする

 ⇒このパラメータが必要、timeout=(connect timeout, read timeout)

・相手サーバーからのレスポンス値を、json形式で呼び出し元へ返す

コードはこんな感じです~

qiita.rb
import requests
import urllib
import json


def post_req(id, password, text, path):
    req = {
        'id': id,
        'pass': password,
        'text': text,
    }
    req = urllib.parse.urlencode(req_data)

    try:
        res = requests.post(path, headers={"Content-Type": "application/x-www-form-urlencoded"}, data=req_data, timeout=(3.0, 5.0))
    except requests.exceptions.Timeout:
        # try exceptでエラー時の処理を記述できる
        print('タイムアウトエラーが発生')
        
    return res.json()

終わりに

pythonのrequestsライブラリはまたいろんなパラメータ設定があり、より高度なリクエストを投げられそうなので、今後はそれらパラメータを調べてみたいです~

参照サイト

0
0
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
0
0