3

i want to get HTTP_REFERER in python flask framework. My route is this:

@app.route('/login')

def login():

    if authenticateForPanel():
        return redirect(url_for("panel"))
    else:               
        ref = request.environ['HTTP_REFERER']

        return render_template('login.html',blogOptions = g.blogOptions,ref=ref)

When i execute this,i got KeyError: 'HTTP_REFERER' with the traceback:

Traceback (most recent call last):
  File "/Users/ozcan/flask/flask/app.py", line 1823, in __call__
    return self.wsgi_app(environ, start_response)
  File "/Users/ozcan/flask/flask/app.py", line 1811, in wsgi_app
    response = self.make_response(self.handle_exception(e))
  File "/Users/ozcan/flask/flask/app.py", line 1809, in wsgi_app
    response = self.full_dispatch_request()
  File "/Users/ozcan/flask/flask/app.py", line 1482, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/Users/ozcan/flask/flask/app.py", line 1480, in full_dispatch_request
    rv = self.dispatch_request()
  File "/Users/ozcan/flask/flask/app.py", line 1466, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/Users/ozcan/Documents/python/app.py", line 318, in login
    ref = request.environ['HTTP_REFERER']
KeyError: 'HTTP_REFERER'

When i first wrote this code it was working.I do not directly call this url.I call localhost:5000/panel and it redirects me to the login method.So basically there should be a referer,am i wrong?

When i print the request.environ['HTTP_REFERER'] it prints None

I also tried with the

ref = request.referrer but it is None

Why it can be happen?Thanks a lot.

saidozcan
  • 2,115
  • 9
  • 27
  • 39

4 Answers4

4

The werkzeug Request wrapper, which flask uses by default, does this work for you: request.referrer

from flask import Flask, request
import unittest

app = Flask(__name__)
@app.route('/')
def index():
    return unicode(request.referrer)

class Test(unittest.TestCase):

    def test(self):
        c = app.test_client()
        resp = c.get('/', headers={'Referer': '/somethingelse'})
        self.assertEqual('/somethingelse', resp.data)

if __name__ == '__main__':
    unittest.main()

But in the more general case, to retrieve the value of a dictionary key specifying a default if the key is not present, use dict.get

DazWorrall
  • 13,682
  • 5
  • 43
  • 37
4

When i first wrote this code it was working.I do not directly call this url.I call localhost:5000/panel and it redirects me to the login method.So basically there should be a referer,am i wrong?

This is not correct. A redirect does not guarantee a referrer. Whether a browser will provide a referrer is browser-specific. Perhaps you were using a different browser that had this behavior at one point? The code you have now is working as best as it can be expected to.

See Will a 302 redirect maintain the referer string?

Community
  • 1
  • 1
Mark Hildreth
  • 42,023
  • 11
  • 120
  • 109
  • then,how can i set a referer? – saidozcan Feb 18 '13 at 16:56
  • 1
    As the answer to the question I linked stated, the most surefire way is to not leave this up to the browsers. Instead, include the URL of the referrer as a parameter in your URL. So, something like `http://example.com/login?referrer=http%3A%2F%2Fexample.com%2Fpanel`. – Mark Hildreth Feb 18 '13 at 17:01
1

The only way I could get request.referrer to not be None is to load the page through <a href="/something"></a>. Redirecting and making regular old HTTP requests did not include a referrer attribute.

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
0

@dm03514 has the right idea, but if you're insistent upon using the environ dictionary, you should be using the get method. Also, how are you testing that it is None, i.e., are you using the interactive interpreter to print the value or are you adding print statements in the body?

An example of how you would do this reasonably:

# snip
else:
    ref = request.environ.get('HTTP_REFERER')
    # You can specify a default return value other than None like so:
    # ref = request.environ.get('HTTP_REFERER', '/')
# snip
Ian Stapleton Cordasco
  • 26,944
  • 4
  • 67
  • 72