<p>您好,我在if-else json响应上的代码有问题,我很确定我的方法是正确的,但是代码在else语句上没有继续</p>
<pre><code>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')
</code></pre>
<p>以下是回应的样本:</p>
<pre><code>{
"multicast_id": xxx,
"success": 1,
"failure": 0,
"canonical_ids": 0,
"results": [
{
"message_id": "xxx"
}
]
}
</code></pre>
<p>或</p>
<pre><code>{
"multicast_id": xxxx,
"success": 0,
"failure": 1,
"canonical_ids": 0,
"results": [
{
"error": "invalid"
}
]
}
</code></pre>
<p>或</p>
<pre><code>{
"message": "Invalid number"
}
</code></pre>
<p>我不确定函数<code>push_notif</code>返回什么,但是如果它返回一个常规的<code>dict</code>,这可能是一个问题,因为您假设键<code>(success, failure and result)</code>存在于dict中,而您提供的上一个响应示例并非如此。因此,通常情况下,异常会引发并停止程序,或者至少在捕获时,结束for循环并退出函数</p>