Support for FastAPI dependencies #128
Replies: 2 comments 9 replies
-
See below for an example of where I'd like to use a dependency... I'm sure there's already parts of the piccolo ecosystem I could use for this, but I mostly did it like this to understand the flow. Please keep in mind that all of this is coming from someone who is not working as a programmer and is also VERY new to Python. Maybe this is really obvious to someone with more experience. This is my first attempt at something that works exactly the way I want to: @reciperouter.get("/me", response_model=t.List[RecipeModelOut])
async def get_users_recipes(conn: HTTPConnection):
token = conn.cookies.get("session")
if not token:
return JSONResponse(
status_code=401,
content="You are not logged in."
)
s = SessionsBase
user = (
s.select(s.user_id)
.where(s.token == conn.cookies.get("session"))
.run_sync()
)
if not user:
return JSONResponse(
status_code=401,
content="Your token is invalid. Please log in again.",
)
user_id = list(map(itemgetter("user_id"), user))
r = Recipe
return await r.select().where(r.author == user_id[0]).run() I'm thinking that this whole part: token = conn.cookies.get("session")
if not token:
return JSONResponse(
status_code=401,
content="You are not logged in."
)
s = SessionsBase
user = (
s.select(s.user_id)
.where(s.token == conn.cookies.get("session"))
.run_sync()
)
if not user:
return JSONResponse(
status_code=401,
content="Your token is invalid. Please log in again.",
)
user_id = list(map(itemgetter("user_id"), user)) could just be separated and then added as a dependency.. But not sure where/how to put it. |
Beta Was this translation helpful? Give feedback.
-
This is a good intro in to how Dependencies in FastAPI work: https://www.jeffastor.com/blog/authentication-dependencies-in-fastapi |
Beta Was this translation helpful? Give feedback.
-
Hi!
Working more with FastAPI makes it clear how big of a role the dependency injection system (https://fastapi.tiangolo.com/tutorial/dependencies/) plays. It would make a lot of sense to implement the support for this in Piccolo for a smooth experience. Afterall, FastAPI seems to be winning the ASGI framework race right now. The goal is to be able to do something like this:
Where
get_current_admin_user
would have to inspect the token and return the BaseUser object. I still haven't wrapped my around the dependcy injection system nor do I know where this should be implemented. Just want to put this here to kick off the discussion.Beta Was this translation helpful? Give feedback.
All reactions