debian

Swagger如何与Debian数据库交互

小樊
46
2025-09-08 23:44:40
栏目: 智能运维

Swagger 本身不直接与数据库交互,需通过后端服务实现,以下是在 Debian 系统中常见的实现方式:

一、基于 Python(Flask)的实现

  1. 安装依赖

    sudo apt update
    sudo apt install python3 python3-pip python3-venv
    pip install flask flask-restplus mysql-connector-python  # 以MySQL为例
    
  2. 编写后端代码

    • 创建 app.py,配置数据库连接并定义 API 路由:
      from flask import Flask
      from flask_restplus import Api, Resource
      import mysql.connector
      
      app = Flask(__name__)
      api = Api(app)
      
      # 数据库配置
      db_config = {
          'host': 'localhost',
          'user': 'your_username',
          'password': 'your_password',
          'database': 'your_database'
      }
      
      @api.route('/users')
      class UserResource(Resource):
          def get(self):
              cnx = mysql.connector.connect(**db_config)
              cursor = cnx.cursor()
              cursor.execute('SELECT * FROM users')
              results = cursor.fetchall()
              cursor.close()
              cnx.close()
              return results
      
      if __name__ == '__main__':
          app.run(debug=True)
      
  3. 集成 Swagger UI

    • 安装 flask-swagger-ui
      pip install flask-swagger-ui
      
    • 在代码中添加 Swagger 配置:
      from flask_swagger_ui import get_swaggerui_blueprint
      
      SWAGGER_URL = '/api-docs'
      API_URL = '/static/swagger.json'
      swaggerui_blueprint = get_swaggerui_blueprint(SWAGGER_URL, API_URL)
      app.register_blueprint(swaggerui_blueprint, url_prefix=SWAGGER_URL)
      
    • 访问 http://localhost:5000/api-docs 查看文档。

二、基于 Node.js(Express)的实现

  1. 安装依赖

    sudo apt install nodejs npm
    npm install express swagger-jsdoc swagger-ui-express mysql2  # 以MySQL为例
    
  2. 编写后端代码

    • 创建 app.js,集成 Swagger 和数据库:
      const express = require('express');
      const swaggerUi = require('swagger-ui-express');
      const mysql = require('mysql2/promise');
      const swaggerJsDoc = require('swagger-jsdoc');
      
      // 数据库连接
      const pool = mysql.createPool({
          host: 'localhost',
          user: 'your_username',
          password: 'your_password',
          database: 'your_database'
      });
      
      // Swagger 配置
      const swaggerDefinition = {
          openapi: '3.0.0',
          info: { title: 'API Docs', version: '1.0.0' }
      };
      const swaggerOptions = {
          swaggerDefinition,
          apis: ['./routes/*.js'] // 指定路由文件
      };
      const swaggerDocs = swaggerJsDoc(swaggerOptions);
      
      // API 路由
      const userRouter = require('./routes/userRoutes')(pool);
      app.use('/api', userRouter);
      
      // 集成 Swagger UI
      app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocs));
      
      app.listen(3000, () => console.log('Server running on port 3000'));
      
  3. 定义路由和模型

    • routes/userRoutes.js 中实现数据库操作:
      const express = require('express');
      const router = express.Router();
      
      router.get('/users', async (req, res) => {
          const [rows] = await pool.query('SELECT * FROM users');
          res.json(rows);
      });
      
      module.exports = (pool) => router;
      

三、关键注意事项

  1. 数据库驱动选择

    • MySQL:mysql-connector-python(Python)、mysql2(Node.js)
    • PostgreSQL:psycopg2(Python)、pg(Node.js)
  2. 安全配置

    • 避免在代码中硬编码数据库凭据,使用环境变量或配置文件管理敏感信息。
    • 生产环境中关闭 Swagger 的公开访问或添加认证机制。
  3. Debian 系统服务化

    • 可将 Python/Node.js 应用配置为系统服务(如 systemd),实现开机自启和进程管理。

通过以上步骤,可在 Debian 系统中通过 Swagger 文档化并测试与数据库交互的 API 接口。

0
看了该问题的人还看了