[英]Python request response - if elif condition not working
嗨,我的代碼在 if else json 響應時遇到問題,我很確定我正在做正確的方法,但代碼不會在 else 語句中繼續。
import requests
import psycopg2
conn = psycopg2.connect(dbname='databasename',user='postgres',password='12345',host='x.x.x.x', port='xxxx') # works correctly
print('success db')
cur = conn.cursor()
cur.execute("SELECT mobile_number FROM users WHERE status='ACTIVE'") # this is my query
conn.commit();
row_count = cur.rowcount
print('This is the number of rows: ', row_count)
result = [mobileNum[0] for mobileNum in cur.fetchall()]
for mobileNum in result:
print('Current Number: ', mobileNum)
pushnotif = push_notif(mobileNum) # This is a function for http request
if pushnotif['success'] == 1 and pushnotif['failure'] == 0 : # This line of code is working and continue the for loop
print('Success!!!')
elif pushnotif['success'] == 0 and pushnotif['failure'] == 1: # This line of code is working but only when I'm printing a sentence like faileedddd!
print(pushnotif['results']['error']) # This doesn't print the result error on http response and exits the for loop
elif pushnotif['message'] == "Invalid number": # This line doesn't work and end the for loops
print(pushnotif['message'])
else: # The code doesn't go here whenever the response is not 200 OK or push_notif['message'] or push_notif['results''error']
print('error')
以下是響應示例:
{
"multicast_id": xxx,
"success": 1,
"failure": 0,
"canonical_ids": 0,
"results": [
{
"message_id": "xxx"
}
]
}
或者
{
"multicast_id": xxxx,
"success": 0,
"failure": 1,
"canonical_ids": 0,
"results": [
{
"error": "invalid"
}
]
}
或者
{
"message": "Invalid number"
}
我不確定 function push_notif
返回什么,但如果它返回常規dict
,這可能是一個問題,因為您假設字典中存在鍵(success, failure and result)
,但情況並非如此您提供的最后一個響應示例。 所以通常一個異常會引發並停止你的程序,或者至少如果被捕獲,會結束 for 循環並退出 function。
例如,假設您最初得到以下響應。
{
"message": "Invalid number"
}
在這里,您的字典只有一個名為message
的鍵。因此,當您使用諸如success
、 failure
之類的鍵檢查響應時,您的程序將停止執行,因為這些鍵不存在於您當前的響應中,並且您的 else 語句將永遠不會執行。
pushnotif = push_notif(mobileNum)
pushlen = len(pushnotif)
if pushlen == 5:
print("This will print if API response is equal to 5", pushnotif)
elif pushlen == 1:
print("This will print if API response is equal to 1", pushnotif)
else:
print("This will print unexpected response", pushnotif)
這是邏輯再次感謝您!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.