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

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

  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)
相关推荐
GIS数据转换器2 分钟前
2025无人机在电力交通中的应用实践
运维·人工智能·物联网·安全·无人机·1024程序员节
Elendill33 分钟前
【Ubuntu】Ubuntu 服务器升级系统操作记录
运维·服务器·ubuntu
北亚数据恢复37 分钟前
服务器数据恢复—Raid5阵列热备盘同步失败,数据恢复揭秘
运维·服务器
利刃大大41 分钟前
【高并发服务器:HTTP应用】十五、HttpRequest请求模块 && HttpResponse响应模块设计
服务器·c++·http·项目
Matana1111 小时前
Vmware中主机ip a没有ip地址
服务器·网络·tcp/ip
征尘bjajmd1 小时前
Java使用okhttp发送get、post请求
java·服务器·数据库
塔能物联运维1 小时前
物联网运维中基于联邦学习的跨设备隐私保护与协同优化技术
运维·物联网
Dreamboat-L2 小时前
使用VMware安装centos的详细流程(保姆级教程)
linux·运维·centos
数字化顾问2 小时前
(114页PPT)华为FusionCloud私有云最佳实践RegionTypeII(附下载方式)
运维·服务器·华为
蓦然回首的风度2 小时前
【运维记录】Centos 7 基础命令缺失
linux·运维·centos