在 Python 中构建 URL 时如何连接路径的组件 [英] How to join components of a path when you are constructing a URL in Python
问题描述
例如,我想将前缀路径加入到/js/foo.js 等资源路径中.
For example, I want to join a prefix path to resource paths like /js/foo.js.
我希望生成的路径相对于服务器的根目录.在上面的例子中,如果前缀是media",我希望结果是/media/js/foo.js.
I want the resulting path to be relative to the root of the server. In the above example if the prefix was "media" I would want the result to be /media/js/foo.js.
os.path.join 在这方面做得很好,但它如何连接路径取决于操作系统.在这种情况下,我知道我的目标是网络,而不是本地文件系统.
os.path.join does this really well, but how it joins paths is OS dependent. In this case I know I am targeting the web, not the local file system.
当您使用已知将在 URL 中使用的路径时,是否有最佳选择?os.path.join 能正常工作吗?我应该自己动手吗?
Is there a best alternative when you are working with paths you know will be used in URLs? Will os.path.join work well enough? Should I just roll my own?
推荐答案
由于从 OP 发布的评论来看,他似乎不想希望在连接中保留绝对 URL"(这是 urlparse.urljoin
的关键工作之一;-),我建议避免这样做.os.path.join
也很糟糕,原因完全相同.
Since, from the comments the OP posted, it seems he doesn't want to preserve "absolute URLs" in the join (which is one of the key jobs of urlparse.urljoin
;-), I'd recommend avoiding that. os.path.join
would also be bad, for exactly the same reason.
所以,我会使用类似 '/'.join(s.strip('/') for s inpieces)
(如果前导 /
必须也可以忽略——如果首部必须是特殊情况,那当然也是可行的;-)
So, I'd use something like '/'.join(s.strip('/') for s in pieces)
(if the leading /
must also be ignored -- if the leading piece must be special-cased, that's also feasible of course;-).
这篇关于在 Python 中构建 URL 时如何连接路径的组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!