Get protocol + host name from URL


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:

I should get:

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
7/22/2018 3:30:46 PM

Accepted Answer

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('' )
result = '{uri.scheme}://{uri.netloc}/'.format(uri=parsed_uri)

# gives
7/22/2018 3:35:14 PM

This is a more verbose version of urlparse. It detects domains and subdomains for you.

From their documentation:

>>> import tldextract
>>> tldextract.extract('')
ExtractResult(subdomain='', domain='cnn', suffix='com')
>>> tldextract.extract('') # United Kingdom
ExtractResult(subdomain='forums', domain='bbc', suffix='')
>>> tldextract.extract('') # Kyrgyzstan
ExtractResult(subdomain='www', domain='worldbank', suffix='')

ExtractResult is a namedtuple, so it's simple to access the parts you want.

>>> ext = tldextract.extract('')
>>> ext.domain
>>> '.'.join(ext[:2]) # rejoin subdomain and domain

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow