我正在使用 Python 3.8
我有一個變數api_url,它代表我從資料庫中提取的 API URL。URL 可以根據我查詢資料庫的方式而改變。
api_url = https://system.company.com/API?%40asset={asset}
我現在想使用api_url包含{asset}變數的 API 獲取請求。
import requests
asset = "BuildingA"
requests.get(f"{api_url}", headers=headers)
但我很確定它不起作用,因為 API 呼叫回傳一個空白回應。我假設 f 字串沒有被{asset}視為變數。
因此,我的問題是如何在 requests.get() 函式{asset}的變數中使用變數?{api_url}
uj5u.com熱心網友回復:
您不能鏈接 f 字串。
所以要么:
api_url = 'https://system.company.com/API'
requests.get(f"{api_url}?asset={asset}")
或者
api_url = 'https://system.company.com/API'
requests.get(api_url, params={'asset': asset})
如果你真的想要一個包含變數的預定義字串,你可以使用格式:
asset_url = 'https://system.company.com/API?asset={asset}'
requests.get(asset_url.format(asset=asset))
uj5u.com熱心網友回復:
我認為如果 api_url 是f-string這可能會識別asset為一個變數。
asset = 'BuildingA'
api_url = f'https://system.company.com/API?@asset={asset}'
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/511294.html
