在if / else语句中无法访问代码块

时间:2018-11-15 16:39:13

标签: python

当使用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结果:

HTTP/1.0 200 OK
Content-Type: application/json
Content-Length: 239
Access-Control-Allow-Origin: *
Server: Werkzeug/0.14.1 Python/3.7.0
Date: Thu, 15 Nov 2018 16:30:01 GMT

{
  "StoreNumber": "42",
  "MainLEC": "XO",
  "MainCircuitID": "xx/xxx/xxxxx/ /TQW /",
  "SprintNUA": "",
  "LastMileCircuitID": "xx/xxxx/xxxx//PA",
  "AnalogCarrier": "XO/BE",
  "SignalingCluster": "ipv4:xx.2.xx.x0x"
}

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"

计数为0,所以我们得到404返回值,所以我知道计数和条件都有效。

如果我在print()之后放一个else:,它将运行,但是循环不会运行。

2 个答案:

答案 0 :(得分:2)

通过在游标上调用EventEmitter,您将耗尽迭代器,而其他任何内容都无法循环通过list()分支。下面的玩具代码演示了这一点,为了更好的实践,我进行了一些更改:

  1. 我使用了else context manager,即使发生错误,它也将为我们处理关闭数据库的过程。
  2. 我已经使用参数化查询来检索值;这些将有助于防止SQL注入。
  3. 我已经演示了使用with来检索结果。尽管直接在游标上进行迭代比预先生成整个结果列表更为有效,但除了将结果分配给有意义的名称之外,它还允许您进行多次迭代。

示例:

.fetchall()

答案 1 :(得分:1)

看起来cur是一个迭代器,而res是对该迭代器的引用。当您调用list(cur)时,它将耗尽迭代器,然后将其丢弃。然后,您尝试遍历res,一无所有,因此您的for循环不执行任何操作。

显而易见的答案是:

    res = list(cur) 
    if len(res) == 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)