Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get referring URL for Flask request

Tags:

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.

like image 944
Robert Guice Avatar asked Feb 18 '15 20:02

Robert Guice


People also ask

How do I find the URL of a referrer?

To check the Referer in action go to Inspect Element -> Network check the request header for Referer like below. Referer header is highlighted. Supported Browsers: The browsers are compatible with HTTP header Referer are listed below: Google Chrome.

What is request referrer in Flask?

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")

How do you get the request object in Flask?

To access the incoming data in Flask, you have to use the request object. The request object holds all incoming data from the request, which includes the mimetype, referrer, IP address, raw data, HTTP method, and headers, among other things.

What is CTX in Flask?

has_app_context is a function in the flask. ctx module that is similar to has_request_context but for the application context rather than the request. after_this_request and has_request_context are a couple of other callables within the flask. ctx package that also have code examples.


2 Answers

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.

like image 151
Selcuk Avatar answered Sep 19 '22 16:09

Selcuk


Thanks to the accepted answer, I set up my app to capture an external referrer and store it in the session. Then when the user signs up I save that value with the user.

from flask import request, g from werkzeug.urls import url_parse  def referral():     url = request.referrer      # if domain is not mine, save it in the session     if url and url_parse(url).host != "example.com":         session["url"] = url      return session.get("url")  @app.before_request def before_request():     g.user = current_user     g.url = referral() 
like image 20
Robert Guice Avatar answered Sep 18 '22 16:09

Robert Guice