当处于if/else状态时无法访问代码块

2024-09-30 20:35:27 发布

您现在位置: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结果:

^{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}之后运行。在


Tags: store代码infordbdatanamescolumn
2条回答

通过在游标上调用list(),您耗尽了迭代器,没有留下任何其他东西让您的else分支循环。下面的玩具代码演示了这一点,为了更好地练习,我做了一些修改:

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

示例:

import sqlite3

with sqlite3.connect(":memory:") as conn: # Using a context manager
    c = conn.cursor()

    c.execute("""
              CREATE TABLE IF NOT EXISTS testing(
                  some_code INTEGER,
                  data TEXT)
              """)

    c.executemany("""
                  INSERT INTO testing VALUES (?, ?)
                  """, [[1, 'hi'], [2, 'bye'], [1, 'something']])

    # Query the new database using a parameterized query
    c.execute("select * from testing where some_code = ?", (1,))

    if len(list(c)) > 0: # Exhausts the iterator and then throws the result away 
        print("Printing result set 1")
        for row in c:
            print(row)
        print("End of result set 1")
        print()

    # Repeat the query
    c.execute("select * from testing where some_code = ?", (1,))
    print("Printing result set 2")
    for row in c: # iterate the cursor 
        print(row)
    print("End of result set 2")
    print()

    # And one more time but using fetchall()
    c.execute("select * from testing where some_code = ?", (1,))
    data = c.fetchall() # Exhaust the iterator but assign a list to a name
    print("Printing result set 3")
    for row in data:
        print(row)
    print("End of result set 3")
    print()

    # And we can keep on printing without re-querying
    print("Printing result set 4")
    for row in data: 
        print(row)
    print("End of result set 4")
    print()

看起来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)

相关问题 更多 >