Get referring URL for Flask request

前端 未结 2 1928
心在旅途
心在旅途 2021-01-01 15:12

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

2条回答
  •  有刺的猬
    2021-01-01 15:30

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

提交回复
热议问题