如何在没有协议或域的情况下获取URL的一部分

时间:2017-02-04 07:25:07

标签: python django

我有

形式的网址
http://example.com/example/a/b/c.html
https//www.example.com/

如何在没有协议或域名的情况下从服务器根获取路径?通过上面的示例,函数应该返回:

/example/a/b/c.html
/

(我正在使用Django:接受依赖此框架的答案!)

2 个答案:

答案 0 :(得分:4)

urlparse模块可以解决这个问题:

from urlparse import urlparse # for python 2
from urllib.parse import urlparse # for python 3

parsed_url = urlparse('http://example.com/abc/cde')
assert parsed_url.path == '/abc/cde'

答案 1 :(得分:2)

您可以使用django path对象的HttpRequest属性,换句话说:

request.path

请参阅docs了解更多