Last Updated: February 25, 2016
·
3.484K
· coreydowning

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.

HerokuRequest gist

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

2 Responses
Add your response

Nice! Not sure this existed back in the day but is a better solution going forward.

over 1 year ago ·