Issue
In my Django app, I need to get the host name from the referrer in request.META.get('HTTP_REFERER')
along with its protocol so that from URLs like:
- https://docs.google.com/spreadsheet/ccc?key=blah-blah-blah-blah#gid=1
- https://stackoverflow.com/questions/1234567/blah-blah-blah-blah
- http://www.example.com
- https://www.other-domain.com/whatever/blah/blah/?v1=0&v2=blah+blah ...
I should get:
- https://docs.google.com/
- https://stackoverflow.com/
- http://www.example.com
- https://www.other-domain.com/
I looked over other related questions and found about urlparse, but that didn't do the trick since
>>> urlparse(request.META.get('HTTP_REFERER')).hostname
'docs.google.com'
Solution
You should be able to do it with urlparse
(docs: python2, python3):
from urllib.parse import urlparse
# from urlparse import urlparse # Python 2
parsed_uri = urlparse('http://stackoverflow.com/questions/1234567/blah-blah-blah-blah' )
result = '{uri.scheme}://{uri.netloc}/'.format(uri=parsed_uri)
print(result)
# gives
'http://stackoverflow.com/'
Answered By - kgr
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.