Way to inject context using middleware?
- Dominant language
- Python
- Stars
- 11.1k
- Forks
- 1k
- Avg merge
- 1d 22h
- Merged PRs (30d)
- 2
Description
I'm registering some middleware for my REST API and I would like to use it to connect to a database and provide the database client to the handlers. However, I can't figure out a way to pass the new object along to the handlers. I assumed it was as simple as calling the `get_response` function with more parameters and defining my handlers to accept additional variables, but now I realize there is more going on before my handlers get called. I then looked into modifying the event dictionary in the Request object as a workaround, but the event is not an exposed property. How can I do this? Other API frameworks that I've worked with allow middleware to modify request objects directly as a way of passing information to the request handlers. I don't see a way to do that here.
To detail what I expected:
```
@app.middleware('http')
def inject_context(event, get_response):
try:
db=boto3.resource("dynamodb", region_name=AWS_REGION).Table(TABLE_NAME)
ctx = { "db": db }
return get_response(event, ctx)
except (ResourceLoadException, ResourceNotExistsError) as err:
{ ... } # LOG AND RETURN 500 RESPONSE
@app.route("/list/things", methods=["GET"], content_types=["application/json"])
def run_get_account(event, ctx):
{ ... } # DO THINGS
```
OR
```
@app.middleware('http')
def inject_context(event, get_response):
try:
db=boto3.resource("dynamodb", region_name=AWS_REGION).Table(TABLE_NAME)
ctx = { "db": db }
event.set_context(ctx) # SOMETHING THAT ALLOWS ME TO ADD THINGS TO THE REQUEST
return get_response(event)
except (ResourceLoadException, ResourceNotExistsError) as err:
{ ... } # LOG AND RETURN 500 RESPONSE
@app.route("/list/things", methods=["GET"], content_types=["application/json"])
def run_get_account(event):
{ ... } # DO THINGS
```
For while I was setting some values globally and accessing them directly from the functions, but doing this creates other issues.
Contributor guide
Research direction
Start by reviewing the HTTP middleware flow, the get_response callback, and the Request object described in the issue. Determine whether middleware can add request context or whether handler signatures must change; done means documenting or implementing a supported way to pass the database client to route handlers while preserving error handling.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- aws, python
- Domain
- api, backend
- Issue type
- Feature
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Needs clarification
- Newbie friendliness
- 35/100