使用请求和 f-string 迭代 url

Iterate over url using request and f-string

我在使用请求库调用 API 端点时尝试遍历电子邮件列表,但是在遍历并尝试使用 f 字符串时我无法转义反斜杠。这是我的代码:

import requests
import json

file = '/usr/datas.json'
with open(file, 'r') as f:
    emails = json.load(f)

for email in emails:
    resp = requests.post(f'https://api.com/public/generic/v3/Load?readData={\"lib\":\"200\",\"debug\":\"false\",\"develfield\":{\"field\":[\"id\",\"suffix\",\"m\"]},\"primaryKey\":{\"mail\":\"{email}\"},\"fieldList\":{\"field\":[\"uid\",\"mail\",\"postalCode\",\"location\",\"phone\",\"fax\",\"l\",\"m\"]}}&responsetype=json', headers=custom_header, verify=False)
    resp.raise_for_status()
    account_data = resp.json()

我试图在我的字符串中引用 {email} 变量,但收到 f-string expression part cannot include a backslash 错误消息。

我试过多种方式转义我的反斜杠,比如创建一个反斜杠变量并在我的 f 字符串中引用它,但没有成功。在不使用 f 字符串的情况下进行循环时,有什么方法可以引用变量吗?

谢谢!

您实际上需要在 f-strings 中 escape the curly braces,而不是引号

You need to double the {{ and }} [to escape them]

import requests
import json

file = '/usr/datas.json'
with open(file, 'r') as f:
    emails = json.load(f)

for email in emails:
    resp = requests.post(f'https://api.com/public/generic/v3/Load?readData={{"lib":"200","debug":"false","develfield":{{"field":["id","suffix","m"]}},"primaryKey":{{"mail":"{email}"}},"fieldList":{{"field":["uid","mail","postalCode","location","phone","fax","l","m"]}}}}&responsetype=json', headers=custom_header, verify=False)
    resp.raise_for_status()
    account_data = resp.json()

此外,考虑使用 dict 和 json.dumps 构建 readData 参数以获得更好的可读性

import requests
import json

file = '/usr/datas.json'
with open(file, 'r') as f:
    emails = json.load(f)

for email in emails:
    data = {
        "lib": "200",
        "debug": "false",
        "develfield": {
            "field": ["id", "suffix", "m"]
        },
        "primaryKey": {"mail": email},
        "fieldList": {
            "field": ["uid", "mail", "postalCode", "location", "phone", "fax", "l", "m"]
        }
    }
    str_data = json.dumps(data)
    resp = requests.post(
        f'https://api.com/public/generic/v3/Load?readData={str_data}&responsetype=json',
        headers=custom_header, verify=False)
    resp.raise_for_status()
    account_data = resp.json()