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

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

  1. 使用 Web 框架搭建
    • Python 和 Flask:Flask 是一个轻量级的 Python Web 框架。示例代码如下:
python 复制代码
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)

还有一个示例比较全面

python 复制代码
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)
相关推荐
你好,帅哥17 分钟前
openssl ,msys2 ,交叉编译
linux·运维·服务器
计算机安禾27 分钟前
【Linux从入门到精通】第36篇:DNS服务探秘——自己搭建一个内网DNS
linux·运维·servlet
Web极客码1 小时前
2026年Linux VPS安全加固清单:SSH、防火墙与审计就绪配置
运维·服务器·数据库
星恒讯工业路由器2 小时前
配网自动化多网融合应用解决方案
运维·自动化
前端技术2 小时前
03_网络层与IP编址:理解网络寻址的核心逻辑
服务器·网络·php
智慧物业老杨2 小时前
智慧物业收费系统的数智化落地实践:从人工硬扛到自动化闭环
运维·自动化
Championship.23.242 小时前
Linux Top 命令族深度解析与实战指南
java·linux·服务器·top·linux调试
techdashen2 小时前
Cloudflare 为何抛弃 NGINX,用 Rust 自研了一个代理
运维·nginx·rust
南城猿2 小时前
保姆级 Ubuntu 部署 禅道
linux·运维·ubuntu
ITHAOGE153 小时前
下载 | Windows Server 2025官方原版ISO映像!(4月更新、标准版、数据中心版、26100.32690)
服务器·windows·科技·微软·电脑