【问题标题】:Using Flask-Injector with Flask-restplus causes an error when calling the api resource使用 Flask-Injector 和 Flask-restplus 调用 api 资源时出错
【发布时间】:2020-01-08 09:54:37
【问题描述】:

我正在尝试使用 Flask-restplus 和 Flask-Flask-Injector 构建一个 api。

我搜索并找不到关于这两个的示例。

所有示例都在 Flask 上,而不是其余的。

我尝试使用以下内容进行构建: ``

from flask import Flask
from flask_restplus import Api, Resource
from flask_injector import FlaskInjector, Injector, inject, singleton  

app = Flask(__name__)
app.secret_key = "123"
api = Api(app=app)  

class MyConf():
    def __init__(self, val: int):
        self.val = val

class MyApi(Resource):
    @inject
    def __init__(self, conf: MyConf):
       self.val = conf.val

    def get(conf: MyConf):
        return {'x': conf.val}, 200


api.add_resource(MyApi, '/myapi')

def configure(binder):
    myConf = MyConf(456)
    binder.bind(
        MyConf,
        to=MyConf(456),
        scope=singleton
    )
    binder.bind(
        MyApi,
        to=MyApi(myConf)
    )

FlaskInjector(app=app, modules=[configure])

app.run(port=555, debug=True)

我是python新手,其实不知道Flask-Injector的这种用法是否正确,所以在浏览器用get方法调用api(myapi)时出现这个错误:

injector.CallError: 调用 MyApi.init(conf=ma​​in.MyConf object at 0x0000026575726988>, api=) 失败:init() 得到了一个意外的关键字参数“api”(注入堆栈:[])

【问题讨论】:

    标签: python flask flask-restplus flask-injector


    【解决方案1】:

    我能够在I opened on github 问题的帮助下解决这个问题,这是代码的更新工作版本:

    app = Flask(__name__)
    app.secret_key = "123"
    api = Api(app=app)  
    
    class MyConf():
        def __init__(self, val: int):
            self.val = val
    
    class MyApi(Resource):
        @inject
        def __init__(self, conf: MyConf, **kwargs): # <- here just added **kwargs to receice the extra passed `api` parameter
           self.val = conf.val
           # Don't know if really needed
           super().__init__(**kwargs)
    
        def get(conf: MyConf):
            return {'x': conf.val}, 200
    
    
    api.add_resource(MyApi, '/myapi')
    
    def configure(binder):
        myConf = MyConf(456)
        binder.bind(
            MyConf,
            to=MyConf(456),
            scope=singleton
        )
        # No need to bind the resource itself
        #binder.bind(
        #   MyApi,
        #   to=MyApi(myConf)
        #)
    
    FlaskInjector(app=app, modules=[configure])
    
    app.run(port=555, debug=True)
    

    【讨论】:

      猜你喜欢
      • 2019-02-13
      • 2013-12-08
      • 1970-01-01
      • 1970-01-01
      • 2018-08-07
      • 1970-01-01
      • 2018-10-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多