Get referring URL for Flask request

空扰寡人 提交于 2020-05-23 05:46:25

问题


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.


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/28593235/get-referring-url-for-flask-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!