Get correct remote_addr on Heroku with Flask
So I spent far too much time debugging why my session were expiring rapidly on Mighty Spring's stage server that runs on Heroku. I finally dug deep enough with logging to find that remote_addr
was returning a different value each time. I created a new Request
class that returns the correct remote_addr
when running on Heroku.
from flask import Request
class HerokuRequest(Request):
"""
`Request` subclass that overrides `remote_addr` with Heroku's
HTTP_X_FORWARDED_FOR when available.
"""
@property
def remote_addr(self):
"""The remote address of the client."""
fwd = self.environ.get('HTTP_X_FORWARDED_FOR', None)
if fwd is None:
return self.environ.get('REMOTE_ADDR')
# sometimes x-forwarded-for contains multiple addresses,
# actual client is first, rest are proxy
fwd = fwd.split(',')[0]
return fwd
## use HerokuRequest class so we get real IPs
app.request_class = HerokuRequest
Written by Corey Downing
Related protips
2 Responses
There is http://werkzeug.pocoo.org/docs/wrappers/#werkzeug.wrappers.BaseRequest.access_route which does exactly the same.
over 1 year ago
·
Nice! Not sure this existed back in the day but is a better solution going forward.
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Python
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#