Loading...
墨滴

我只想

2021/07/01  阅读:68  主题:极简黑

python openapi使用全流程

python openapi使用全流程

本文章介绍使用swagger-coden和yaml文件生成openapi使用的客户端和服务端

安装swagger-coden

  • macos
brew install swagger-codegen
  • docker
docker pull swaggerapi/swagger-codegen-cli-v3

编译成不同语言的代码库

  • yaml文件
---
openapi: 3.0.1
info:
  title: 我的openapi
  description: 我的第一个openapi应用
  version: 1.0.0
servers:
  - url: https://127.0.0.1:8080/v1.0
  - url: http://127.0.0.1:8080/v1.0

paths:
  /deliveryGroups:
    get:
      summary: 获取所有交付组
      operationId: delivery_group_get_all
      responses:
        200:
          description: 操作成功
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref"#/components/schemas/DeliveryGroup"
        401:
          $ref"#/components/responses/401"
        404:
          $ref"#/components/responses/404"
      security:
        - api_key: []
components:
  schemas:
    DeliveryGroupId:
      type: string
      format: uuid
      description: 交付组 ID。系统自动分配,不可更改。对应于应用镜像 ID。
      example: "6395a2c0-9e1e-4e88-bc04-82b87c6aa23b"

    DeliveryGroupName:
      type: string
      description: 组
      example: Group

    DeliveryGroup:
      type: object
      description: delivery base。
      properties:
        id:
          $ref"#/components/schemas/DeliveryGroupId"
        name:
          $ref"#/components/schemas/DeliveryGroupName"
    CommonReturn:
      type: object
      properties:
        detail:
          type: string
          description: 详情
          example: No authorization token provided
        status:
          typeinteger
          description: 状态码
          example: 401
        title:
          type: string
          description: 标题
          example: Unauthorized
        type:
          type: string
          description: 错误类型
          enum:
            - Internal
            - Parameters
            - Auth
            - None
      example:
        title: 授权错误
        status: 403
        detail: 用户名或密码错误
        type: Auth
  responses:
    202:
      description: 更新成功
      content:
        application/json:
          schema:
            $ref"#/components/schemas/CommonReturn"
          examples:
            参数错误:
              value:
                title: 更新成功
                status: 202
                detail: 更新成功
                type: None
    400:
      description: 操作失败
      content:
        application/json:
          schema:
            $ref"#/components/schemas/CommonReturn"
          examples:
            参数错误:
              value:
                title: 参数错误
                status: 401
                detail: 用户名或密码错误
                type: Auth

    401:
      description: 操作失败
      content:
        application/json:
          schema:
            $ref"#/components/schemas/CommonReturn"
          examples:
            授权错误:
              value:
                title: 授权错误
                status: 401
                detail: 用户名或密码错误
                type: Auth
    403:
      description: 操作失败
      content:
        application/json:
          schema:
            $ref"#/components/schemas/CommonReturn"
          examples:
            权限错误:
              value:
                title: 权限错误
                status: 403
                detail: 提供的凭据没有权限操作此资源
                type: Auth
    404:
      description: 操作失败
      content:
        application/json:
          schema:
            $ref"#/components/schemas/CommonReturn"
          examples:
            未找到资源:
              value:
                title: 未找到资源
                status: 404
                detail: 请求的资源不存在
                type: Parameters

  securitySchemes:
    api_key:
      description: 使用成功登录时,使用 cookies 中的 JSESSIONID 标记授权。
      type: apiKey
      name: JSESSIONID
      in: cookie
  • 使用Makefile
.PHONY: server_api_lib client_api_lib js_client_api_lib single_html2 all clean

CMD =
ROOT_DIR =
ifdef USE_DOCKER
 ROOT_DIR := /opt/data
 CMD := docker run --rm  -v ${PWD}:${ROOT_DIR} swaggerapi/swagger-codegen-cli-v3
else
 ROOT_DIR := .
 CMD := swagger-codegen
endif

SPEC_FILE = ${ROOT_DIR}/openapi.yaml

server_api_lib:
 echo "building server lib"
 ${CMD} generate -i ${SPEC_FILE} -l python-flask -o ${ROOT_DIR}/rcac_server_openapi -c ${ROOT_DIR}/python-flask-server.json

py_client_api_lib:
 echo "building client lib"
 ${CMD} generate -i ${SPEC_FILE} -l python -o ${ROOT_DIR}/py_rcac_client_openapi -c ${ROOT_DIR}/python-client-lib.json

js_client_api_lib:
 echo "building javascript client lib"
 ${CMD} generate -i ${SPEC_FILE} -l javascript -o ${ROOT_DIR}/js_rcac_client_openapi -c ${ROOT_DIR}/javascript-client-lib.json

single_html2:
 echo "building html2 doc"
 ${CMD} generate -i ${SPEC_FILE} -l html2 -o ${ROOT_DIR}/html2

all: server_api_lib py_client_api_lib js_client_api_lib single_html2

clean:
 rm -rf py_client_openapi
 rm -rf server_openapi
 rm -rf js_client_openapi
 rm -rf html2

使用生成的服务端代码

import connexion
from flask_cors import CORS
from waitress import serve
from rcac_server_openapi import encoder
import rcac_server_openapi


def init(host, port, thread_num):
    yaml_path = rcac_server_openapi.__path__[0] + "/swagger/swagger.yaml"
    yaml_dir = rcac_server_openapi.__path__[0] + "/swagger/"
    print(yaml_path)
    connexion_app = connexion.App(__name__, specification_dir=yaml_dir)
    connexion_app.add_api("swagger.yaml")

    connexion_app.app.json_encoder = encoder.JSONEncoder

    serve(connexion_app.app, host=host, port=port, threads=thread_num)

init("127.0.0.1", 8000, 3)

使用生成的客户端代码

# import apis into sdk package
from rcac_client_openapi.api.default_api import DefaultApi
# import ApiClient
from rcac_client_openapi.api_client import ApiClient
from rcac_client_openapi.configuration import Configuration
# import models into sdk package
from rcac_client_openapi.models.common_return import CommonReturn
from rcac_client_openapi.models.delivery_group import DeliveryGroup
from rcac_client_openapi.models.delivery_group_id import DeliveryGroupId
from rcac_client_openapi.models.delivery_group_name import DeliveryGroupName

import rcac_client_openapi as swagger_client

configuration = swagger_client.Configuration()
configuration.host = "http://{0}:{1}/{2}".format("127.0.0.1", 8000, "v1.0")
api_client = swagger_client.ApiClient(configuration)
api_instance = swagger_client.DefaultApi(api_client)

# yaml文件设置api_key,所以这里需要设置下
configuration.auth_settings = lambda : {"api_key": {"type""api_key""in""header""key""Cookie""value":"JSESSIONID=sasdfdsa"}}
ret = api_instance.delivery_group_get_all()
print(ret)

结束

具体例子在仓库https://gitee.com/luoweichui/openapi中

- END -

我只想

2021/07/01  阅读:68  主题:极简黑

作者介绍

我只想