encode / starlette

The little ASGI framework that shines. 🌟
https://www.starlette.io/
BSD 3-Clause "New" or "Revised" License
10.26k stars 934 forks source link

Dependency injection in views #713

Closed espositofulvio closed 5 years ago

espositofulvio commented 5 years ago

This is directed to Tom mainly, as I've just watched his presentation at PyCon2017 in Portland.

In that presentation he advocated for getting away from the request/response model for views towards a model where views just declare the expected parameters which would be injected with the help of type annotations, something like:

async def order_list(user: User, filter: QueryParam[str]) -> List[Order]:
  ...

Is this pursued in starlette? I was thinking of doing something similar with the help of IoC container like Lagom or rodi, which I plan to use in other parts of my architecture, not just the web side. Just wanted to know if there has been any effort in this direction. Thanks

dmontagu commented 5 years ago

For what it's worth, this is precisely the approach used in FastAPI, which is built on top of Starlette.

Docs here

espositofulvio commented 5 years ago

@dmontagu thanks, I had a look at that and noticed it is oriented towards building APIs. I'm currently focusing on Starlette for now as I'm not working only on building APIs and I'd like to have something like that in Starlette as well.

tomchristie commented 5 years ago

Heya! Yeah FastAPI is the closest thing for now.

704 will make it far easier to subclass the Route behavior, which is the point at which we drop out of ASGI, and into the endpoint request/response.

We could absolutely have a subclass there that uses DI, question is really if we'd ever do this in the Starlette package itself, or if we'd leave that type of design decision to higher level frameworks.

I could even see myself coming back to an APIStar implementation, now that we've actually got proper fundamentals in place. It was problematic before, because it attempted to use depenency injection all the way through, including middleware stages, and exception handling, and was attempting to handle either WSGI, or ASGI. That coupled with seeing a huge amount of work that needed doing in the async space was why I eventually chose to ditch it. If it was exclusively DI for the route itself, it'd be a far nicer design.

tomchristie commented 5 years ago

Going to close this off for now, since it's not something I'm planning to act on right now, but there could be potential there in the future.