[英]request.post() works at URL but yields 500 response when ran in python
當我將 payload1 的值復制並粘貼到 API url 中時,我收到 200 響應。 這是 URL:
https://api.usaspending.gov/api/v2/bulk_download/awards/
但是,當我通過 request.post() 在 python 中運行代碼時,我得到了 500 響應。 我的最終目標是將返回的 zip 文件放入 python 中,這樣我就可以自動提取數據。 我是 API 新手,對 python 有一些經驗,所以我希望代碼盡可能簡單。 提前致謝。
import requests
payload1 = {
"filters": {
"prime_award_types": [
"A",
"B",
"C",
"D",
"IDV_A",
"IDV_B",
"IDV_B_A",
"IDV_B_B",
"IDV_B_C",
"IDV_C",
"IDV_D",
"IDV_E",
"02",
"03",
"04",
"05",
"10",
"06",
"07",
"08",
"09",
"11"
],
"agency": 66,
"date_type": "action_date",
"date_range": {"start_date":"2019-01-01","end_date":"2019-01-31"}
},
"columns": [],
"file_format": "csv"
}
response = requests.post('https://api.usaspending.gov/api/v2/bulk_download/awards/', data = payload1)
嘗試在 post 方法中使用json
關鍵字 arg 作為有效負載:
url = "https://api.usaspending.gov/api/v2/bulk_download/awards/"
requests.post(url, json=payload1)
您可以將有效負載存儲在文件中,將其加載到變量中並將其傳遞給請求庫的發布 function。 所以你會是:
import requests
with open('desired_payload.txt','rt') as f:
desired_payload = f.read()
url = 'https://api.usaspending.gov/api/v2/bulk_download/awards/'
headers = {'Content-Type': 'application/json'}
resp = requests.post(url, headers=headers, data=desired_payload)
if resp.status_code == 200:
print('success')
print(resp.content)
else:
print('fail')
使用此腳本,我可以收到一個成功的響應,其中包含 zip 文件的status_url
、 file_name
、 file_url
……。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.