python Python 3.x中请求模块的一般用例错误处理示例

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python Python 3.x中请求模块的一般用例错误处理示例相关的知识,希望对你有一定的参考价值。

import json
import sys

import requests

def exit_with_error(e):
  sys.stderr.write(str(e))
  sys.exit(1)


def request(url, **kwds):
    try:
        repsonse = requests.get(url, **kwds)
    except RequestException as e:
        exit_with_error(e)
  
    if response.status_code == 200:
        try:
          return response.json()
        except ValueError as e:
          exit_with_error(e)

    sys.stderr.write(str(e))
    try:
        sys.stderr.write(json.dumps(response.json(), indent=2))
    except (TypeError, json.JSONDecodeError):
        pass
import json
import sys

import requests


def request(url, auth=None, headers=None, params=None, data=None, method='get'):
    try:
        if data is not None:
          repsonse = requests.get(url, auth=auth, headers=headers, params=params)
        kwds = dict(auth=auth, headers=headers, params=params, data=data)
        response = getattr(requests, method)(url, **kwds)
        if response.status_code == 200:
            return response.json()
        print(json.dumps(response.json(), indent=2), file=sys.stderr)
        response.raise_for_status()
    except (RequestException, HTTPError, TypeError, ValueError,
            json.JSONDecodeError) as e:
        print(str(e), file=sys.stderr)
        sys.exit(1)

以上是关于python Python 3.x中请求模块的一般用例错误处理示例的主要内容,如果未能解决你的问题,请参考以下文章