在我的 Django 应用程序中,我需要从 request.META.get('HTTP_REFERER')
中的引用者那里获取主机名及其协议(protocol),以便从以下 URL 获取:
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.example/whatever/blah/blah/?v1=0&v2=blah+blah
我应该得到:
https://docs.google.com/
https://stackoverflow.com/
http://www.example.com
https://www.other-domain.example/
我查看了其他相关问题并发现了有关 urlparse 的信息,但此后并没有解决问题
>>> urlparse(request.META.get('HTTP_REFERER')).hostname
'docs.google.com'
最佳答案
您应该可以使用 urlparse
(文档: 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/'
关于python - 从 URL 获取协议(protocol) + 主机名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9626535/