使用Python编写的all_requests()函数,实现多种请求的快速响应
发布时间:2023-12-26 12:37:02
下面是使用Python编写的all_requests()函数,该函数可以用于快速响应多种请求。该函数使用了Python的requests库,它可以发送HTTP请求并获取响应。
import requests
def all_requests(url, method='GET', headers=None, params=None, data=None, json=None):
"""
发送HTTP请求并获取响应
参数:
- url: 请求的URL
- method: 请求方法,默认为'GET'
- headers: 请求头,默认为None
- params: 请求参数,默认为None
- data: 请求体,默认为None
- json: JSON格式的请求体,默认为None
返回:
- response: 响应对象
异常:
- requests.exceptions.RequestException: 发送请求时可能会抛出异常
"""
try:
if method == 'GET':
response = requests.get(url, headers=headers, params=params)
elif method == 'POST':
response = requests.post(url, headers=headers, params=params, data=data, json=json)
elif method == 'PUT':
response = requests.put(url, headers=headers, params=params, data=data, json=json)
elif method == 'DELETE':
response = requests.delete(url, headers=headers, params=params)
else:
raise ValueError("Invalid HTTP method")
return response
except requests.exceptions.RequestException as e:
print("An error occurred:", str(e))
return None
下面是一个使用示例,使用该函数发送不同类型的请求并获取响应:
# 发送GET请求
response = all_requests('https://api.github.com/users/username')
print(response.status_code)
print(response.json())
# 发送POST请求
data = {'name': 'John', 'age': 30}
response = all_requests('https://httpbin.org/post', method='POST', data=data)
print(response.status_code)
print(response.json())
# 发送PUT请求
data = {'name': 'John', 'age': 30}
response = all_requests('https://httpbin.org/put', method='PUT', data=data)
print(response.status_code)
print(response.json())
# 发送DELETE请求
response = all_requests('https://httpbin.org/delete', method='DELETE', params={'id': 1})
print(response.status_code)
print(response.json())
在上面的示例中,我们使用了不同的HTTP方法(GET、POST、PUT、DELETE)发送请求,并打印了响应的状态码和JSON响应体。
这样,我们就可以快速响应各种类型的请求并获取响应了。
