【发布时间】:2021-02-21 22:58:18
【问题描述】:
我需要通过他们的 API 将数据推送到网站,我正在尝试找到一种方法来使用 F-string 来传递数据列表中的变量,但找不到方法。
这是我迄今为止尝试过的:
today = datetime.date.today()
tomorrow = today + datetime.timedelta(days = 1)
#trying to pass *tomorrow* value with f-string below
data = f'[{"date": "{tomorrow}", "price": {"amount": 15100}}]'
response = requests.put('https://api.platform.io/calendar/28528204', headers=headers, data=data)
我怎样才能做到这一点?
【问题讨论】:
-
data可以是字典。 -
@BrownieInMotion 这是什么意思?
-
您应该使用
{{来表示f-strings 中的文字{,但@BrownieInMotion 是正确的;您应该直接使用数据结构:data = [{"date": tomorrow, "price": {"amount": 15100}}]。requests.put将自动使用它,但如果您必须将其转换为 json,请使用json.dumps(data)。不要自己构造 json 字符串,始终使用json模块。