使用FlaskRestplus、API和多个蓝图大摇大摆

2024-10-01 11:23:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用Flask和Flask Restplus构建一个非常复杂的微服务。
它将有许多端点,因此我将每个端点组织到一个单独的蓝图中。

  • 目前,我正在为flaskrestplus和API的使用而挣扎,并将多个蓝图与swagger结合使用
  • 我希望能够将我的蓝图的所有端点都放入内置的API中,但这似乎行不通。在
  • 我可以通过postman访问我的端点,但是swaggerui没有显示任何内容。:(

下面的示例代码和目录结构应该会给您一个提示,让您了解我的想法:

.
├── endpoints
│   ├── endpointa.py
│   ├── endpointb.py
│   ├── endpointc.py
│   └── __init__.py
├── __init__.py
└── run.py

我的maininit.py如下所示:

^{pr2}$

在端点a.py相应的蓝图:

from os import environ
import json, ast, syslog
import requests
import gc
from flask import Flask, Blueprint, logging, jsonify, request, Response
from flask_restplus import Resource, Api

endpointa_api = Blueprint('endpointa_api', __name__)

@endpointa_api.route('testa', methods=['GET'])
def testa():
    ...


@endpointa_api.route('testa/<string:testa_id>', methods=['GET', 'POST'])
def testa_id():
    ...

再说一遍:

我可以通过postman访问我的端点,但是swagger用户界面没有显示任何内容:

enter image description here

通常,我会使用类似于

api.add_resource(TestClass, api_prefix + 'test')

但这似乎不可能有多个蓝图。在

有谁能告诉我如何在api中添加/注册这些蓝图(endpointa_api、endpointb呬api和endpointc_api)?


Tags: frompyimportapiflask内容swaggerplus
1条回答
网友
1楼 · 发布于 2024-10-01 11:23:52

使用Flask Restplus有两种可能的解决方案:

  • 使用Flask RestPlus命名空间
  • 把你的蓝图变成烧瓶RestPlusApis

您可以在文档中阅读这两方面的内容: https://flask-restplus.readthedocs.io/en/stable/scaling.html

名称空间

Flask-RESTPlus provides a way to use almost the same pattern as Flask’s blueprint. The main idea is to split your app into reusable namespaces.

from flask_restplus import Api

from .namespace1 import api as ns1
from .namespace2 import api as ns2
# ...
from .namespaceX import api as nsX

api = Api(
    title='My Title',
    version='1.0',
    description='A description',
    # All API metadatas
)

api.add_namespace(ns1)
api.add_namespace(ns2)
# ...
api.add_namespace(nsX)

蓝图API

Here’s an example of how to link an Api up to a Blueprint.

^{pr2}$

Using a blueprint will allow you to mount your API on any url prefix and/or subdomain in you application:

from flask import Flask
from apis import blueprint as api

app = Flask(__name__)
app.register_blueprint(api, url_prefix='/api/1')
app.run(debug=True)

相关问题 更多 >