Get referring URL for Flask request

Robert Guice picture Robert Guice · Feb 18, 2015 · Viewed 14.9k times · Source

When a user visits our site and signs up, how can I capture which website they came from?

Be it search, a PR website, etc. I don't care what page from our site they visited, I just want to know which marketing efforts are giving us the most signups.

I know Google Analytics can probably do this but I'd like to have something internal for reference as well.

Answer

Selcuk picture Selcuk · Feb 18, 2015

request.referrer contains the URL the request came from, although it might not be sent by the client for various reasons.

The attribute takes its value from the Referer (not a typo!) header:

referrer = request.headers.get("Referer")

or, using the Flask shortcut:

referrer = request.referrer

See this tutorial for an example.