【问题标题】:How to use Python format function in this case在这种情况下如何使用 Python 格式函数
【发布时间】:2022-12-22 23:28:56
【问题描述】:

我需要通过链接发送请求。以下链接有效,可以返回我需要的内容:

response = requests.get(
    """https://pangeare.freshservice.com/api/v2/assets?include=type_fields&filter="updated_at:>%272022-10-09%27"&page="""+ str(page),
    auth = ('xxxxxxxxx', ''),
    headers = headers
)

您可以看到 updated_at 过滤器被硬编码到 url 中。如果我尝试使用格式函数填充 updated_at 值,它将返回 400

response = requests.get(
   """https://pangeare.freshservice.com/api/v2/assets?include=type_fields&filter="updated_at:>{0}"&page=""".format('2022-10-09') + str(page),
    auth = ('xxxxxxxxxxxx', ''),
    headers = headers
)

在这种情况下使用格式函数的合适方法是什么?

【问题讨论】:

    标签: python


    【解决方案1】:

    执行整个操作的 pythonic 方法是使用 params option

    您也可以使用 f-strings 而不是 .format()

    BASE_URL_PATH = "https://pangeare.freshservice.com/api/v2/assets"
    
    date_str = "2022-10-09"
    
    response = requests.get(
        BASE_URL_PATH,
        params={
            "include": "type_fields",
            "filter": f""updated_at:>%27{date_str}%27"",
            "page": page,
        }
        auth = ('xxxxxxxxxxxx', ''),
        headers = headers
    )
    

    【讨论】:

    • 为什么使用这种格式 f""updated_at:>%27{date_str}%27"",而不是 updated_at:>%27{date_str}%27"?
    • 在您的帖子中,过滤器查询中包含引号,因此它们仍需要包含在字符串中。 filter="updated_at:>{0}" 大概这就是为什么你首先用 """ 包装的原因。
    猜你喜欢
    • 2023-03-29
    • 1970-01-01
    • 2021-05-21
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 2015-11-30
    • 2017-05-16
    • 2012-10-06
    相关资源
    最近更新 更多