将 Flask-Injector 与 Flask-restplus 配合使用会导致调用 api 资源时出错



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

我搜索了一下,找不到这两个一起的例子。

所有的例子都在Flask上,而不是restplus上。

我尝试使用以下方法进行构建: ``

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( 时出现此错误:

注射器。调用错误:调用 MyApi。init(conf=<<strong>main.MyConf 对象在 0x0000026575726988>, api=( 失败:init(( 得到一个意外的关键字参数 'api' (注入堆栈: [](

借助我在 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)

最新更新