【问题标题】:How to build dynamic URL string for REST API endpoint call? [closed]如何为 REST API 端点调用构建动态 URL 字符串? [关闭]
【发布时间】:2021-06-09 15:06:49
【问题描述】:

我的问题是关于使用现有 REST API 的 Python 代码。该脚本基于requests

假设我们有以下基本 URL:

www.something.com/search/countries/{country_code}/cities/{city_code}/

为了忽略 URL 编码,我们假设代码是数字的。

看来format 是用实际值替换“占位符”的完美方法。

URL.format(country_code = ..., city_code-... )

pythonic够了吗?

【问题讨论】:

    标签: python python-requests rest


    【解决方案1】:

    我认为.format 是一个非常好的方法,但它不是超级可读的。您可以使用 Python f-strings 使其更具可读性,例如:

    country_code = 'foo'
    city_code = 'bar'
    url = f'www.something.com/search/countries/{country_code}/cities/{city_code}/'
    

    f 将告诉 Python 用上面定义的变量插入大括号内的值。

    【讨论】:

      猜你喜欢
      • 2021-08-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-23
      • 2013-03-12
      • 2013-01-13
      相关资源
      最近更新 更多