python - 从 URL 获取协议(protocol) + 主机名

标签 python django

在我的 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 (文档: python2python3 ):

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/

相关文章:

python - Django 的 collectstatic 有什么意义?

python - 如何向用户显示问题并使用 "if" "else"语句专家系统 django 进行比较?

jquery - 如何使用 Jquery 更改按钮单击时的 django 外键对象文本选择字段?

python - PIL image.convert ("RGB") 是否将图像转换为 sRGB 或 Adob​​eRGB?

python - 如何有条件地跳过pytest中 fixture 的实例化?

python - 在 python 中对字典的字典列表进行排序

django - Django结合了DetailView和FormView

python - python的切片有多快

Python - 我需要了解旧式类吗?

python - 在 Elastic Beanstalk Postgresql 中创建 Django super 用户