Request.environ['HTTP_REFERER'] Is None
Solution 1:
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
Solution 2:
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.
Solution 3:
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.
Solution 4:
@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
Post a Comment for "Request.environ['HTTP_REFERER'] Is None"