如何用swagger为我的Python Flask应用程序定义一个基本端点?



我正在尝试用Swagger构建一个简单的Flask应用程序。到目前为止,经过几次教程后,这是我的main.py的样子:

import logging
import os
import random
from flask_restx import Api, Resource, fields
from src import create_app
app = create_app(os.getenv('env'))
api = Api(app, version='1.0', title='Sample API',
description='A sample API', doc='/api')
ns = api.namespace('userinfo', description='Python Microservice')
user = api.model('user', {
'name': fields.String(required=True, description='Employee Name'),
'role': fields.String(required=True, description='Employee Role'),
})
USERS = {'user_1000': dict(name="Elizabeth Lemon", role="Head"), 'user_1001': dict(name="Jack Donaghy", role="CEO"),
'user_1003': dict(name="Kenneth Parcell", role="Page")}
resource_fields = api.model('Resource', {
'name': fields.String,
'role': fields.String
})

@ns.route('/')
@api.doc(responses={200: 'Success', 201: 'Created'})
class UserInfo(Resource):
"""View list of all users, POST to add new user"""
def get(self):
"""List  all users"""
return [{'id': u_id, 'user_info': user_info} for u_id, user_info in USERS.items()]
@api.doc(body=resource_fields)
def post(self):
"""Create a new user"""
data = api.payload
user_id = f"user_{random.randint(1004, 9999)}"
USERS[user_id] = dict(name=data['name'], role=data['role'])
logging.info(f"Created user {user_id} for {data['name']}")
return dict(user_id=user_id), 201

if __name__ == '__main__':
app.run(debug=True)

create_app()函数在一个__init__.py中定义如下:

def create_app(config_name):
app = Flask(__name__)
app.config.from_object(config_by_name[config_name])
setup_logging(app)
return app

现在,当我转到localhost:5000/api时,我看到swagger页面正确地加载了GET/POST文档。然而,当我点击localhost:5000时,我得到了URL not found错误-可以理解,因为我还没有定义/路由-这就是我被卡住的地方!!如何在main.py中定义/路由?据我所知,目前服务的所有端点都是/userinfo/(GET, POST)和/api。我想添加/端点以方便对应用程序是否启动进行简单检查

我是在Python中用Flask构建微服务的新手。集成swagger实际上改变了main.py的面貌,因为在没有swagger的早期,我所有的路由都用app.route('/')注释,所以我可以有一个/端点。

默认情况下,flask-restx使用命名空间名称来构造url (/<name>前缀),但您可以通过path参数显式指定所有url的前缀。比如:

ROOT_NS = api.namespace(
'section-name-that-will-be-displayed-at-swagger--fill-free-to-rename',
path='/'
)

最新更新