首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用use_kwargs装饰器时,flask_apispec库使Flask应用程序崩溃

使用use_kwargs装饰器时,flask_apispec库使Flask应用程序崩溃
EN

Stack Overflow用户
提问于 2021-11-07 20:58:19
回答 1查看 156关注 0票数 0

我正在使用flask_restful、flask_apispec和棉花糖在Python3.8中构建Restful API。当我启用use_kwargs装饰器时,我的应用程序在使用TypeError: post() takes 1 positional argument but 2 were given的帖子上崩溃

如果能帮助我解决这个bug,我将不胜感激。

代码语言:javascript
复制
# requirements.txt
aniso8601==9.0.1
apispec==5.1.1
certifi==2021.10.8
charset-normalizer==2.0.7
click==8.0.3
Flask==2.0.2
flask-apispec==0.11.0
Flask-RESTful==0.3.9
gunicorn==20.1.0
idna==3.3
itsdangerous==2.0.1
Jinja2==3.0.2
MarkupSafe==2.0.1
marshmallow==3.14.0
pytz==2021.3
requests==2.26.0
six==1.16.0
tableauserverclient==0.17.0
urllib3==1.26.7
webargs==8.0.1
Werkzeug==2.0.2
代码语言:javascript
复制
from apispec import APISpec
from flask import Flask, request
from flask_restful import Resource, Api
from apispec.ext.marshmallow import MarshmallowPlugin
from flask_apispec.extension import FlaskApiSpec
from marshmallow import Schema, fields, post_load, ValidationError
from flask_apispec.views import MethodResource
from flask_apispec import use_kwargs, marshal_with

app = Flask(__name__)  # Flask app instance initiated
api = Api(app)  # Flask restful wraps Flask app around it.
app.config.update({
    'APISPEC_SPEC': APISpec(
        title='Kube Controller',
        version='v1',
        plugins=[MarshmallowPlugin()],
        openapi_version='2.0.0'
    ),
    'APISPEC_SWAGGER_URL': '/swagger/',  # URI to access API Doc JSON
    'APISPEC_SWAGGER_UI_URL': '/swagger-ui/'  # URI to access UI of API Doc
})
docs = FlaskApiSpec(app)


class AwesomeRequestSchema(Schema):
    api_type = fields.String(required=True)

    @post_load
    def create(self, data, **kwargs):
        return MyAPI(**data)


class MyAPI:
    def __init__(self, api_type):
        self.api_type = api_type
        self.message = "hi"


class AwesomeAPI(MethodResource, Resource):
    @use_kwargs(AwesomeRequestSchema)
    @marshal_with(AwesomeRequestSchema, code=200, description='Something created')
    def post(self):
        """
        POST
        """
        try:
            schema = AwesomeRequestSchema()
            data = schema.load(request.json)
            print(data.api_type)
            return request.json
        except ValidationError as err:
            return err.messages


api.add_resource(AwesomeAPI, '/')
docs.register(AwesomeAPI)

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

谢谢!

EN

回答 1

Stack Overflow用户

发布于 2021-11-26 07:40:11

我也有同样的问题。use_kwargs装饰器将尝试填充AwesomeRequestSchema对象并将其注入到post()方法中:https://flask-apispec.readthedocs.io/en/latest/api_reference.html#flask_apispec.annotations.use_kwargs

要修复,请替换

代码语言:javascript
复制
def post(self):

使用

代码语言:javascript
复制
def post(self, populated_request_object):
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69876473

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档