requests发送http请求

  开发

from enum import Enum
import requests
import time

class RequestMethod(Enum):
    """
    请求的方法.
    """
    GET = 'GET'
    POST = 'POST'
    PUT = 'PUT'
    DELETE = 'DELETE'

def request(req_method: RequestMethod, url: str):
    timeout = 5
    try_counts = 3

    for i in range(0, try_counts):
        try:
            response = requests.request(req_method.value, url=url, timeout=timeout)
            http_code = response.status_code

            if http_code == 200:
                return response.json()
            else:
                print(response.json(), http_code)

        except Exception as error:
            print(f"请求:{url}, 发生了错误: {error}")
            time.sleep(3)


if __name__ == '__main__':
    print(request(RequestMethod.GET,"https://api.uomg.com/api/rand.music?sort=热歌榜&format=json"))

LEAVE A COMMENT

Captcha Code