You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用flask-injector将接口作为函数参数注入

使用Flask-Injector将接口作为函数参数注入到Connexion API

我来帮你梳理下如何结合Flask-Injector和Connexion实现依赖注入,让你的RestaurantsProvider能作为参数注入到API路由函数里。

1. 补全并完善绑定配置

首先你需要完成Binder的绑定逻辑,把RestaurantsProvider模块注册到Injector,同时正确初始化FlaskInjector关联你的Connexion应用:

from connexion.resolver import RestyResolver
import connexion
from injector import Binder, Injector, Module, inject, provider
from flask_injector import FlaskInjector

# 你的RestaurantsProvider模块(修正了返回逻辑,确保返回指定数量的条目)
class RestaurantsProvider(Module):
    @inject
    def __init__(self, items: list=[]):
        self._items = items
    
    @provider
    def get(self, number_of_items: int=5) -> list:
        if not self._items:
            return []
        if number_of_items > len(self._items):
            number_of_items = len(self._items)
        return self._items[:number_of_items]

# 定义依赖绑定规则
def configure(binder: Binder) -> None:
    # 绑定RestaurantsProvider实例,这里可以传入模拟数据作为初始条目
    binder.bind(
        RestaurantsProvider, 
        to=RestaurantsProvider(items=[
            {"id": 1, "name": "Downtown Pizza"},
            {"id": 2, "name": "Lakeview Burger"},
            {"id": 3, "name": "Mountain Sushi"}
        ])
    )

# 创建Connexion应用并加载API规范
app = connexion.FlaskApp(__name__, specification_dir='./')
# 使用RestyResolver自动匹配路由与对应模块的函数
app.add_api('openapi.yaml', resolver=RestyResolver('api'))

# 初始化FlaskInjector,关联Connexion底层的Flask实例和绑定配置
FlaskInjector(app=app.app, modules=[configure])

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

2. 在API路由函数中注入依赖

接下来,你需要在路由函数中通过@inject装饰器声明依赖,让Flask-Injector自动注入RestaurantsProvider实例。假设你的路由函数放在api/restaurants.py(对应RestyResolver的路径规则):

from injector import inject
from your_module import RestaurantsProvider  # 替换为你的实际模块路径

# 直接在路由函数上使用@inject,声明需要注入的依赖
@inject
def get_restaurants(provider: RestaurantsProvider, number_of_items: int = 5):
    # 直接使用注入的provider实例调用方法
    return provider.get(number_of_items)

如果你的OpenAPI规范里的operationId设置为restaurants.get_restaurants,RestyResolver会自动匹配到这个函数,请求进来时Flask-Injector就会把RestaurantsProvider实例注入进来。

3. 关键注意事项

  • 关联正确的Flask实例:初始化FlaskInjector时必须传入app.app(Connexion底层的Flask对象),而不是Connexion应用本身。
  • 依赖函数必须被标记:只有用@inject装饰的函数,才能被FlaskInjector识别并注入依赖。
  • RestyResolver路径匹配:确保你的文件结构和OpenAPI路径对应,比如/restaurants路径对应api/restaurants.py中的函数。

这样配置后,当API收到请求时,Flask-Injector会自动完成依赖注入,你可以直接在路由函数中使用RestaurantsProvider的功能了。

内容的提问来源于stack exchange,提问作者Navendra

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 10:01:59