如何创建伪服务器,伪接口

发布于:2025-05-11 ⋅ 阅读:(19) ⋅ 点赞:(0)

创建伪接口一般是用于模拟真实接口的行为,以便在开发和测试过程中进行使用,以下是一些常见的创建伪接口的方法:

  1. 使用 Web 框架搭建
    • Python 和 Flask:Flask 是一个轻量级的 Python Web 框架。示例代码如下:

from flask import Flask, jsonify

app = 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  # 导入CORS



app = 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':
        # 生成token
        token = str(uuid.uuid4())
        # 设置token有效期为1小时
        expires_at = time.time() + 3600
        valid_tokens[token] = expires_at

        return jsonify({
            "token": token,
            "status": 0,
            "expires_in": 3600,
            "message": "success"
        }), 200
    else:
        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"}), 401

    token = auth_header.split(' ')[1]

    # 验证token
    if 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())
        }
    }), 200


if __name__ == '__main__':
    app.run(host='127.0.0.1', port=11188, debug=True)


网站公告

今日签到

点亮在社区的每一天
去签到