Sanic: X-Request-Id header

Created on 27 Sep 2017  ·  6Comments  ·  Source: sanic-org/sanic

There is a Flask example http://blog.mcpolemic.com/2016/01/18/adding-request-ids-to-flask.html
But how can we properly do it with sanic since there is no flask.g?

Most helpful comment

There is an example for this: https://github.com/channelcat/sanic/blob/master/examples/log_request_id.py

It uses an external dependency https://github.com/Skyscanner/aiotask-context (disclaimer: I'm the maintainer).

All 6 comments

One way would be using middleware. You could have a request middleware that reads the header and adds the request_id field to the request itself (it's a dict). Do whatever processing you would there, and reattach the outbound request_id in the response middleware as the X-Request-Id header.

Thank you, that works, inside my HTTPMethodView class I am getting that changed request. But how can I get access to this request object inside my RequestIdFilter? If I from sanic import request, that will not be the right one.

I assume those are your own abstractions? If that's the case I can only help if you'd provide snippets or something. But in general it largely depends on how are you delivering the request to the filter. I'd assume that you'd want it to be passed?

In any case, consider your request a context for the current eh... request? Pass it around as such. I'm not sure this style scales well with more complex pieces of code, so I'm interested in hearing how others handle this too.

There is an example for this: https://github.com/channelcat/sanic/blob/master/examples/log_request_id.py

It uses an external dependency https://github.com/Skyscanner/aiotask-context (disclaimer: I'm the maintainer).

argaen, thanks, your sollution is a great help! I still wonder - is there a way to access through request object, because this aiotask_context looks like a hack. I suppose we can somehow define logger inside HTTPMethodView's get method where we already have request object, but then we could not use our logger outside of this view.

I guess there are other work arounds but may require more manual work like propagating the request wherever you need it. The only simple way that we found is using the aiotask-context package. Yes, feels a bit hacky but the logic is not super complicated.

Another solution is to wait until https://www.python.org/dev/peps/pep-0550/ gets accepted so this is available natively in Python :P.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

woutor picture woutor  ·  3Comments

misakar picture misakar  ·  4Comments

mobdim picture mobdim  ·  4Comments

1067511899 picture 1067511899  ·  3Comments

eseglem picture eseglem  ·  4Comments