给我写一个通用的响应码类
时间: 2024-03-18 20:40:54 浏览: 11
好的,以下是一个通用的响应码类的示例:
```python
class ResponseCode:
SUCCESS = 200
CREATED = 201
ACCEPTED = 202
BAD_REQUEST = 400
NOT_AUTHORIZED = 401
FORBIDDEN = 403
NOT_FOUND = 404
METHOD_NOT_ALLOWED = 405
INTERNAL_SERVER_ERROR = 500
NOT_IMPLEMENTED = 501
SERVICE_UNAVAILABLE = 503
```
这个类包含了一些常见的HTTP响应码,可以根据需要进行扩展。在代码中使用这个类可以提高可读性和可维护性,例如:
```python
if response.status_code == ResponseCode.SUCCESS:
print("请求成功")
else:
print("请求失败,错误码:", response.status_code)
```
相关问题
给我写一个java的通用的响应码类
好的,以下是一个Java语言的通用响应码类的示例:
```java
public class ResponseCode {
public static final int SUCCESS = 200;
public static final int CREATED = 201;
public static final int ACCEPTED = 202;
public static final int BAD_REQUEST = 400;
public static final int NOT_AUTHORIZED = 401;
public static final int FORBIDDEN = 403;
public static final int NOT_FOUND = 404;
public static final int METHOD_NOT_ALLOWED = 405;
public static final int INTERNAL_SERVER_ERROR = 500;
public static final int NOT_IMPLEMENTED = 501;
public static final int SERVICE_UNAVAILABLE = 503;
}
```
这个类也包含了一些常见的HTTP响应码,使用方式与之前的Python示例类似。在Java中,我们通常使用常量来表示响应码,因此将这些响应码定义为静态常量是一个不错的选择。可以根据需要进行扩展,例如添加自定义的响应码。
```java
public class ResponseCode {
// 常见的HTTP响应码
// ...
// 自定义响应码
public static final int CUSTOM_ERROR_CODE = 1000;
}
```
在代码中使用这个类也可以提高可读性和可维护性,例如:
```java
if (responseCode == ResponseCode.SUCCESS) {
System.out.println("请求成功");
} else {
System.out.println("请求失败,错误码:" + responseCode);
}
```
通过python封装一个通用接口请求
以下是一个简单的 Python 封装通用接口请求的示例:
```python
import requests
def request_api(url, method='GET', headers=None, params=None, data=None, json=None):
"""发送 API 请求并返回响应结果"""
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(f"Unsupported request method: {method}")
response.raise_for_status() # 如果响应状态码不是 2xx,抛出异常
return response.json()
# 示例用法
url = 'https://api.example.com/users'
params = {'page': 1, 'per_page': 10}
headers = {'Authorization': 'Bearer <access_token>'}
response = request_api(url, method='GET', headers=headers, params=params)
print(response)
```
这个函数接受以下参数:
- `url`:API 的 URL。
- `method`:请求方法,支持 GET、POST、PUT 和 DELETE。
- `headers`:请求头,它是一个字典类型。
- `params`:请求参数,它也是一个字典类型。
- `data`:POST 或 PUT 请求时的请求体,它是一个字符串类型。
- `json`:POST 或 PUT 请求时的 JSON 格式请求体,它是一个字典类型。
函数返回 API 响应的 JSON 格式数据。如果响应状态码不是 2xx,它将引发一个异常。