AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / coding / 问题 / 79595515
Accepted
JL Peyret
JL Peyret
Asked: 2025-04-28 05:26:15 +0800 CST2025-04-28 05:26:15 +0800 CST 2025-04-28 05:26:15 +0800 CST

urlparse/urlsplit 和 urlunparse,Pythonic 方法是什么?

  • 772

背景(但不是仅限 Django 的问题)是 Django 测试服务器不会在其响应和请求 URL 中返回方案或 netloc。

例如,我得到了/foo/bar,并且我希望以 结束http://localhost:8000/foo/bar。

urllib.parse.urlparse (但并没有那么复杂urllib.parse.urlsplit)使得从测试 URL 和我已知的服务器地址收集相关信息变得容易。看起来比必要更复杂的是,通过urllib.parse.urlcompose添加 scheme 和 netloc 来重新组合一个新的 URL ,这个 URL 需要位置参数,但没有文档说明它们是什么,也不支持命名参数。同时,解析函数返回的是不可变的元组……

def urlunparse(components):
    """Put a parsed URL back together again.  This may result in a ..."""

我确实让它工作了,请参阅下面的代码,但它看起来真的很笨拙,围绕我需要首先将解析元组转换为列表,然后在所需的索引位置修改列表的部分。

有没有更 Pythonic 的方式?

示例代码:


from urllib.parse import urlsplit, parse_qs, urlunparse, urlparse, urlencode, ParseResult, SplitResult

server_at_ = "http://localhost:8000"
url_in = "/foo/bar"  # this comes from Django test framework I want to change this to "http://localhost:8000/foo/bar"

from_server = urlparse(server_at_)
print("  scheme and netloc from server:",from_server)


print(f"{url_in=}")
from_urlparse = urlparse(url_in)

print("  missing scheme and netloc:",from_urlparse)

#this works
print("I can rebuild it unchanged :",urlunparse(from_urlparse))

#however, using the modern urlsplit doesnt work (I didn't know about urlunsplit when asking)
try:
    print("using urlsplit", urlunparse(urlsplit(url_in)))
#pragma: no cover pylint: disable=unused-variable
except (Exception,) as e: 
    print("no luck with urlsplit though:", e)


#let's modify the urlparse results to add the scheme and netloc
try:
    from_urlparse.scheme = from_server.scheme
    from_urlparse.netloc = from_server.netloc
    new_url = urlunparse(from_urlparse)
except (Exception,) as e: 
    print("can't modify tuples:", e)


# UGGGH, this works, but is there a better way?
parts = [v for v in from_urlparse]
parts[0] = from_server.scheme
parts[1] = from_server.netloc

print("finally:",urlunparse(parts))

示例输出:

  scheme and netloc from server: ParseResult(scheme='http', netloc='localhost:8000', path='', params='', query='', fragment='')
url_in='/foo/bar'
  missing scheme and netloc: ParseResult(scheme='', netloc='', path='/foo/bar', params='', query='', fragment='')
I can rebuild it unchanged : /foo/bar
no luck with urlsplit though: not enough values to unpack (expected 7, got 6)
can't modify tuples: can't set attribute
finally: http://localhost:8000/foo/bar
python
  • 1 1 个回答
  • 46 Views

1 个回答

  • Voted
  1. Best Answer
    furas
    2025-04-28T06:48:04+08:002025-04-28T06:48:04+08:00

    如果您在 Django 中需要它,那么我发现有问题的request.build_absolute_uri()

    如何在 Django 中获取完整/绝对 URL(带域名)? - 代码日志

    我没有测试过,但它也许解决了 Django 中的这个问题。

    其他模块/框架可能也有自己的功能。

    我记得scrapy用于抓取 HTML 的模块有自己的函数response.urljoin()可以将相对 URL 转换为绝对 URL。


    至于模块中的功能urllib:

    你必须使用

    • urlsplit使用urlunsplit(使用较少的值)
    • urlparsewith urlunparse(使用更多值)

    有一个“隐藏”函数_replace(),它使用替换的值创建新的 ParseResult。

    new_urlparse = from_urlparse._replace(scheme=from_server.scheme, netloc=from_server.netloc)
    

    通常我只需要urljoin()

    server_at_ = "http://localhost:8000"  # base 
    url_in = "/foo/bar"                   # relative url
    
    absolute_url = urljoin(server_at, url_in)
    
    • 2

相关问题

  • 如何将 for 循环拆分为 3 个单独的数据框?

  • 如何检查 Pandas DataFrame 中的所有浮点列是否近似相等或接近

  • “load_dataset”如何工作,因为它没有检测示例文件?

  • 为什么 pandas.eval() 字符串比较返回 False

  • Python tkinter/ ttkboostrap dateentry 在只读状态下不起作用

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    重新格式化数字,在固定位置插入分隔符

    • 6 个回答
  • Marko Smith

    为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会?

    • 2 个回答
  • Marko Smith

    VScode 自动卸载扩展的问题(Material 主题)

    • 2 个回答
  • Marko Smith

    Vue 3:创建时出错“预期标识符但发现‘导入’”[重复]

    • 1 个回答
  • Marko Smith

    具有指定基础类型但没有枚举器的“枚举类”的用途是什么?

    • 1 个回答
  • Marko Smith

    如何修复未手动导入的模块的 MODULE_NOT_FOUND 错误?

    • 6 个回答
  • Marko Smith

    `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它?

    • 3 个回答
  • Marko Smith

    在 C++ 中,一个不执行任何操作的空程序需要 204KB 的堆,但在 C 中则不需要

    • 1 个回答
  • Marko Smith

    PowerBI 目前与 BigQuery 不兼容:Simba 驱动程序与 Windows 更新有关

    • 2 个回答
  • Marko Smith

    AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String”

    • 1 个回答
  • Martin Hope
    Fantastic Mr Fox msvc std::vector 实现中仅不接受可复制类型 2025-04-23 06:40:49 +0800 CST
  • Martin Hope
    Howard Hinnant 使用 chrono 查找下一个工作日 2025-04-21 08:30:25 +0800 CST
  • Martin Hope
    Fedor 构造函数的成员初始化程序可以包含另一个成员的初始化吗? 2025-04-15 01:01:44 +0800 CST
  • Martin Hope
    Petr Filipský 为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会? 2025-03-23 21:39:40 +0800 CST
  • Martin Hope
    Catskul C++20 是否进行了更改,允许从已知绑定数组“type(&)[N]”转换为未知绑定数组“type(&)[]”? 2025-03-04 06:57:53 +0800 CST
  • Martin Hope
    Stefan Pochmann 为什么 {2,3,10} 和 {x,3,10} (x=2) 的顺序不同? 2025-01-13 23:24:07 +0800 CST
  • Martin Hope
    Chad Feller 在 5.2 版中,bash 条件语句中的 [[ .. ]] 中的分号现在是可选的吗? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench 为什么双破折号 (--) 会导致此 MariaDB 子句评估为 true? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng 为什么 `dict(id=1, **{'id': 2})` 有时会引发 `KeyError: 'id'` 而不是 TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String” 2024-03-20 03:12:31 +0800 CST

热门标签

python javascript c++ c# java typescript sql reactjs html

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve