当使用if/else
语句验证数据是否返回正确的状态代码时,我在循环中解析响应的代码将完全无法访问。在
以下工作如预期。
class Circuit(Resource):
def get(self, store):
print('USAGE: Received a request at CIRCUIT for Store ' + store )
conn = sqlite3.connect('store-db.db')
cur = conn.cursor()
res = cur.execute('SELECT * FROM Circuit WHERE StoreNumber like ' + store)
for r in res:
column_names = ["StoreNumber", "MainLEC", "MainCircuitID","SprintNUA","LastMileCircuitID", "AnalogCarrier", "SignalingCluster"]
data = [r[0], r[1], r[2], r[3], r[4], r[5], r[6]]
datadict = {column_names[itemindex]:item for itemindex, item in enumerate(data)}
return(datadict, 200)
200结果:
^{pr2}$404结果(未找到数据,但仍返回200)
HTTP/1.0 200 OK
Content-Type: application/json
Content-Length: 5
Access-Control-Allow-Origin: *
Server: Werkzeug/0.14.1 Python/3.7.0
Date: Thu, 15 Nov 2018 16:31:14 GMT
null
这样就可以了,但是我想检查no data found
,所以我编写了一个条件来获取行数。下面是它的使用示例。在
代码示例
class Circuit(Resource):
def get(self, store):
print('USAGE: Received a request at CIRCUIT for Store ' + store )
conn = sqlite3.connect('store-db.db')
cur = conn.cursor()
res = cur.execute('SELECT * FROM Circuit WHERE StoreNumber like ' + store)
if len(list(cur)) == 0:
return('No data', 404)
else:
for r in res:
column_names = ["StoreNumber", "MainLEC", "MainCircuitID","SprintNUA","LastMileCircuitID", "AnalogCarrier", "SignalingCluster"]
data = [r[0], r[1], r[2], r[3], r[4], r[5], r[6]]
datadict = {column_names[itemindex]:item for itemindex, item in enumerate(data)}
return(datadict, 200)
200结果:
HTTP/1.0 200 OK
Content-Type: application/json
Content-Length: 5
Access-Control-Allow-Origin: *
Server: Werkzeug/0.14.1 Python/3.7.0
Date: Thu, 15 Nov 2018 16:35:53 GMT
null
数据以null
的形式返回,经过打印测试后,我发现在for r in res:
我的代码变得无法访问。我已经核实了所有的压痕。在
404结果:
HTTP/1.0 404 NOT FOUND
Content-Type: application/json
Content-Length: 10
Access-Control-Allow-Origin: *
Server: Werkzeug/0.14.1 Python/3.7.0
Date: Thu, 15 Nov 2018 16:37:17 GMT
"No data"
count是0
,所以我们得到404的返回,所以我知道count和conditional都在工作。在
{{cd7}将不在cd6}之后运行。在
通过在游标上调用
list()
,您耗尽了迭代器,没有留下任何其他东西让您的else
分支循环。下面的玩具代码演示了这一点,为了更好地练习,我做了一些修改:with
context manager,它将为我们处理关闭数据库,即使在发生错误的情况下。在.fetchall()
来检索结果。尽管直接在光标上迭代比预先生成整个结果列表更有效,但是除了将结果分配给有意义的名称之外,它允许您多次迭代。在示例:
看起来
cur
是迭代器,res
是迭代器的引用。当您调用list(cur)
时,它会耗尽迭代器,然后您将该数据丢弃。然后尝试遍历res
,没有剩下的东西,所以for循环什么也不做。在显而易见的答案是:
相关问题 更多 >
编程相关推荐