AttributeError: 'Provide' object has no attribute (FastAPI)

See original GitHub issue

i trying to create an app with DI. Example: Application example (multiple containers)

fastapi==0.70.0 dependency-injector==4.36.2

I got this error when the service is called: Traceback:

Traceback (most recent call last):
  File "/usr/local/lib/python3.7/dist-packages/uvicorn/protocols/http/httptools_impl.py", line 375, in run_asgi
    result = await app(self.scope, self.receive, self.send)
  File "/usr/local/lib/python3.7/dist-packages/uvicorn/middleware/proxy_headers.py", line 75, in __call__
    return await self.app(scope, receive, send)
  File "/usr/local/lib/python3.7/dist-packages/fastapi/applications.py", line 208, in __call__
    await super().__call__(scope, receive, send)
  File "/usr/local/lib/python3.7/dist-packages/starlette/applications.py", line 112, in __call__
    await self.middleware_stack(scope, receive, send)
  File "/usr/local/lib/python3.7/dist-packages/starlette/middleware/errors.py", line 181, in __call__
    raise exc
  File "/usr/local/lib/python3.7/dist-packages/starlette/middleware/errors.py", line 159, in __call__
    await self.app(scope, receive, _send)
  File "/usr/local/lib/python3.7/dist-packages/starlette/middleware/cors.py", line 84, in __call__
    await self.app(scope, receive, send)
  File "/usr/local/lib/python3.7/dist-packages/starlette/exceptions.py", line 82, in __call__
    raise exc
  File "/usr/local/lib/python3.7/dist-packages/starlette/exceptions.py", line 71, in __call__
    await self.app(scope, receive, sender)
  File "/usr/local/lib/python3.7/dist-packages/starlette/routing.py", line 656, in __call__
    await route.handle(scope, receive, send)
  File "/usr/local/lib/python3.7/dist-packages/starlette/routing.py", line 259, in handle
    await self.app(scope, receive, send)
  File "/usr/local/lib/python3.7/dist-packages/starlette/routing.py", line 61, in app
    response = await func(request)
  File "/usr/local/lib/python3.7/dist-packages/fastapi/routing.py", line 227, in app
    dependant=dependant, values=values, is_coroutine=is_coroutine
  File "/usr/local/lib/python3.7/dist-packages/fastapi/routing.py", line 161, in run_endpoint_function
    return await run_in_threadpool(dependant.call, **values)
  File "/usr/local/lib/python3.7/dist-packages/starlette/concurrency.py", line 39, in run_in_threadpool
    return await anyio.to_thread.run_sync(func, *args)
  File "/usr/local/lib/python3.7/dist-packages/anyio/to_thread.py", line 29, in run_sync
    limiter=limiter)
  File "/usr/local/lib/python3.7/dist-packages/anyio/_backends/_asyncio.py", line 805, in run_sync_in_worker_thread
    return await future
  File "/usr/local/lib/python3.7/dist-packages/anyio/_backends/_asyncio.py", line 743, in run
    result = func(*args)
  File "/usr/local/lib/python3.7/dist-packages/dependency_injector/wiring.py", line 605, in _patched
    result = fn(*args, **to_inject)
  File "./app/api/v1/users.py", line 23, in get_all
    users = service_user.get_all()
AttributeError: 'Provide' object has no attribute 'get_all'

containers.py

from dependency_injector import containers, providers

from app import redis
from app.services import userservice, sampleservice
import logging.config

class Core(containers.DeclarativeContainer):

    config = providers.Configuration()

    logging = providers.Resource(
        logging.config.dictConfig,
        config=config.logging,
    )


class Gateways(containers.DeclarativeContainer):

    config = providers.Configuration()

    redis_client = providers.Resource(
        redis.init_redis_client,
        host=config.redis.host,
        port=config.redis.port
    )


class Services(containers.DeclarativeContainer):

    config = providers.Configuration()
    gateways = providers.DependenciesContainer()

    sampleservice = providers.Factory(
        sampleservice.Service,
        redis=gateways.redis_client,
    )

    user = providers.Factory(
        userservice.Service,
        redis=gateways.redis_client,
    )


class Application(containers.DeclarativeContainer):

    config = providers.Configuration()

    core = providers.Container(
        Core,
        config=config.core,
    )

    gateways = providers.Container(
        Gateways,
        config=config.gateways,
    )

    services = providers.Container(
        Services,
        config=config.services,
        gateways=gateways
    )

userservice.py

from aioredis import Redis

class Service:
    def __init__(self, redis: Redis) -> None:
        self._redis = redis

    def get_all(self) :
        return []

routes

from typing import List
from fastapi import APIRouter, Depends
from dependency_injector.wiring import inject, Provide
from app.containers import Application
from app.services import userservice
from app.models import usermodels

router = APIRouter()


@router.get(
    "/",
    response_model=List[usermodels.UserRead],
)
@inject
def get_all(
    service_user: userservice.Service = Depends(
        Provide[Application.services.user]),
):
    """
    Retrieve details about a all users.
    """
    users = service_user.get_all()
    print("users", users)

    return users

main.py

import sys

from fastapi import FastAPI, Depends
from starlette.middleware.cors import CORSMiddleware
from dependency_injector.wiring import inject, Provide
from app.containers import Application
import config
from app.api.v1 import api_router


def create_app() -> FastAPI:
    container = Application()
    container.config.from_yaml('config.yml')
    container.wire(modules=[sys.modules[__name__]])

    app = FastAPI()
    app.add_middleware(
        CORSMiddleware,
        allow_origins=config.ALLOWED_HOSTS,
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )
    app.container = container
    app.include_router(api_router)
    return app


app = create_app()

What i’m doing wrong ?

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Comments:11 (6 by maintainers)

github_iconTop GitHub Comments

1reaction
rmk135commented, Oct 23, 2021

Hi @ricardo17coelho ,

You need to update line container.wire(modules=[sys.modules[__name__]]) in main.py. This line should point to the modules where you’re using Provide. In your case, it’s routers module. I don’t see where you keep the routes, but it should be something like that:

from myapp import routers

...

container.wire(modules=[routers])

Also, you can wire a container with whole packages: container.wire(packages=[api_package]). Hope that helps.

0reactions
rmk135commented, Nov 21, 2021

It works now.

Good, I think the last issue was related to the version.

But i think that the error (or one of them) was that “async” word was missing on the route methode declaration.

I tested wiring with both examples and wasn’t able to reproduce the error. I’ll close that issue, but feel free to comment if needed.

Read more comments on GitHub >

github_iconTop Results From Across the Web

'Provide' object has no attribute 'test' - Stack Overflow
Fast API with Dependency-injector Python getting strategy_service.test(Test(name, id)) AttributeError: 'Provide' object has no attribute 'test'.
Read more >
Injection return provide object not actual dependency ... - GitHub
data = self.repo.get_by_id(id) AttributeError: 'Provide' object has no attribute 'get_by_id'. Why? i'am using v2.5.1.
Read more >
Wiring — Dependency Injector 4.41.0 documentation
Wiring feature provides a way to inject container providers into the ... FastAPI example: ... AttributeError: 'Provide' object has no attribute 'pop'
Read more >
tiangolo/fastapi - Gitter
Hi. I have a problem with FastAPI. I've read Query Parameters in which it's mentioned that: You could also use Enums the same...
Read more >
Testing Dependencies with Overrides - FastAPI
For these cases, your FastAPI application has an attribute app.dependency_overrides , it is a simple dict . To override a dependency for testing, ......
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found