在我的 Django 应用程序中,我需要从引用者那里获取主机名request.META.get('HTTP_REFERER')及其协议,以便从以下 URL 获取:
request.META.get('HTTP_REFERER')
https://docs.google.com/spreadsheet/ccc?key=blah-blah-blah-blah#gid=1
https://codingdict.com/questions//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://https://codingdict.com/questions//
https://www.other-domain.example/
我查看了其他相关问题并发现了有关 urlparse 的信息,但这并没有起到作用,因为
>>> urlparse(request.META.get('HTTP_REFERER')).hostname 'docs.google.com'
你应该能够做到这一点urlparse(文档:python2,python3):
urlparse
from urllib.parse import urlparse # from urlparse import urlparse # Python 2 parsed_uri = urlparse('https://codingdict.com/questions//1234567/blah-blah-blah-blah' ) result = '{uri.scheme}://{uri.netloc}/'.format(uri=parsed_uri) print(result) # gives 'https://codingdict.com/questions/'