当前位置: 首页 > news >正文

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

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

  1. 使用 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)

相关文章:

  • 阿里云OSS+CDN自动添加文章图片水印配置指南
  • 差动讯号(3)弱耦合与强耦合
  • Python序列化的学习笔记
  • 物业企业绩效考核制度与考核体系
  • java: Compilation failed: internal java compiler error 报错解决方案
  • 关于一些平时操作系统或者软件的步骤转载
  • STM32f103 标准库 零基础学习之点灯
  • MGP-STR:用于场景文本识别的多粒度预测
  • OSPF综合实验报告
  • RPA 浏览器自动化:高效扩展与智能管理的未来
  • RabbitMQ深入学习
  • CenOS7切换使用界面
  • STM32硬件I2C驱动OLED屏幕
  • 牛客周赛round91
  • Vue 两种导航方式
  • 让fixe和absolute根据锚点元素定位
  • python如何提取Chrome中的保存的网站登录用户名密码?
  • 2021-11-16 C++歌手去掉2最高2最低均分
  • 《从零构建大模型》PDF下载(中文版、英文版)
  • [面试]SoC验证工程师面试常见问题(六)高速接口篇
  • 韩国执政党总统候选人更换方案被否决,金文洙候选人资格即刻恢复
  • 国常会:研究深化国家级经济技术开发区改革创新有关举措等
  • 四川资阳市原市长王善平被双开,“笃信风水,大搞迷信活动”
  • 红场阅兵即将开始!中国人民解放军仪仗队亮相
  • 保利42.41亿元竞得上海杨浦东外滩一地块,成交楼面单价超8万元
  • 巴基斯坦信德省卡拉奇发生爆炸