使用 request 和 f-string 迭代 url。

12 浏览
0 Comments

使用 request 和 f-string 迭代 url。

这个问题已经有答案了

在使用 .format (或 f-string) 时如何转义大括号 ({})?

如何在 f-strings 中转义花括号? [重复]

我想在使用 requests 库调用 API 端点时迭代一个电子邮件列表,但是在迭代过程中并试图使用 f-string 时,我无法转义反斜杠。这是我的代码:

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 表达式部分不能包含反斜杠 的错误消息。

我尝试多种方式转义反斜杠,如创建一个反斜杠变量并在我的 f-string 中引用它,但没有运气。是否有在循环时引用变量而不使用 f-string 的方法?

谢谢!

admin 更改状态以发布 2023年5月24日
0
0 Comments

实际上你需要在f-strings中转义花括号,而不是引号。点击这里了解更多关于此问题的信息。

你需要双倍输入{{}}[来转义它们]

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()

此外,建议使用字典和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()

0