如何创建伪服务器,伪接口
创建伪接口一般是用于模拟真实接口的行为,以便在开发和测试过程中进行使用,以下是一些常见的创建伪接口的方法:
- 使用 Web 框架搭建:
- Python 和 Flask:Flask 是一个轻量级的 Python Web 框架。示例代码如下:
from flask import Flask, jsonifyapp = Flask(__name__)@app.route('/api/data', methods=['GET'])
def get_data():# 这里返回模拟的数据,例如一个字典,将被转换为JSON格式mock_data = {"message": "这是模拟的接口数据","data": [1, 2, 3]}return jsonify(mock_data)if __name__ == '__main__':app.run(debug=True)
还有一个示例比较全面
from flask import Flask, request, jsonify, make_response
import uuid
import time
from flask_cors import CORS # 导入CORSapp = Flask(__name__)
CORS(app)# 模拟存储有效令牌
valid_tokens = {}@app.route('/api/auth', methods=['POST'])
def auth():"""认证接口,返回token"""# 检查请求内容类型if request.content_type != 'application/x-www-form-urlencoded':return jsonify({"error": "Content-Type must be application/x-www-form-urlencoded"}), 400# 获取表单数据username = request.form.get('username')password = request.form.get('password')# 验证用户名和密码(示例中使用固定值)if username == 'admin' and password == 'admin':# 生成tokentoken = str(uuid.uuid4())# 设置token有效期为1小时expires_at = time.time() + 3600valid_tokens[token] = expires_atreturn jsonify({"token": token,"status": 0,"expires_in": 3600,"message": "success"}), 200else:return jsonify({"error": "Invalid credentials"}), 401@app.route('/api/getrunprocess', methods=['POST'])
def get_run_process():"""获取运行进程信息的接口"""# 检查请求头中的Authorization字段auth_header = request.headers.get('Authorization')if not auth_header or not auth_header.startswith('Bearer '):return jsonify({"error": "Authorization header is missing or invalid"}), 401token = auth_header.split(' ')[1]# 验证tokenif token not in valid_tokens or valid_tokens[token] < time.time():return jsonify({"error": "Invalid or expired token"}), 401# 模拟返回运行进程数据return jsonify({"code": 200,"message": "success","data": [{"name": "UnrealEngine","status": "running","address": "::ffff:127.0.0.1","PORT": 8080,"start_time": "2023-05-10T10:30:00Z"},{"name": "GameServer","status": "running","address": "::ffff:127.0.0.1","PORT": 8081,"start_time": "2023-05-10T10:35:00Z"}]}), 200@app.route('/api/killrunprocess', methods=['POST'])
def kill_run_process():"""终止运行进程的接口"""# 检查请求内容类型if request.content_type != 'application/json':return jsonify({"error": "Content-Type must be application/json"}), 400# 获取JSON数据data = request.get_json()if not data:return jsonify({"error": "Invalid JSON payload"}), 400# 提取必要参数process_type = data.get('type')address = data.get('address')port = data.get('PORT')# 验证必要参数if not process_type or not address or port is None:return jsonify({"error": "Missing required parameters: type, address, PORT"}), 400# 模拟处理结果time.sleep(0.5) # 模拟处理延迟# 返回成功响应return jsonify({"code": 200,"message": f"Process {process_type} on {address}:{port} terminated successfully","data": {"status": "terminated","type": process_type,"address": address,"port": port,"terminated_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())}}), 200if __name__ == '__main__':app.run(host='127.0.0.1', port=11188, debug=True)