Skip to content

Dependency fails when provided as generator #12

@joeblackwaslike

Description

@joeblackwaslike
def get_db():
    db = current_app.extensions['sqlalchemy'].db
    try:
        yield db.session
    except Exception:
        db.session.rollback()
    finally:
        db.session.close()


@dependant
def create_model(data: MagicClientCreate, db: Session = Depends(get_db)):
    magic_client = MagicClient(**data.dict())
    db.add(magic_client)
    db.commit()
    db.refresh(magic_client)
    return magic_client

Fails with the following error:

AttributeError: 'generator' object has no attribute 'add'

I see towards the end of solve_dependencies generator support was commmented out

        else:
            solved = await run_in_threadpool(call, **sub_values)
        if sub_dependant.name is not None:
            values[sub_dependant.name] = solved
        if sub_dependant.cache_key not in dependency_cache:
            dependency_cache[sub_dependant.cache_key] = solved
        """
        # generator support
        elif is_gen_callable(call) or is_async_gen_callable(call):
            stack = scope.get("fastapi_astack") if scope else None
            if stack is None:
                raise RuntimeError(
                    asynccontextmanager_error_message
                )  # pragma: no cover
            solved = await solve_generator(
                call=call, stack=stack, sub_values=sub_values
            )
        """

    return values, errors, dependency_cache

I'm curious why this is, this is the most common use case for Depends in FastAPI?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions