检查Sqlite3查询是否返回空Flask

时间:2018-11-15 15:13:31

标签: python flask sqlite

我在形成条件以检查对我的API的响应是否为null时遇到了麻烦。我正在使用Flask和SQLite3模块。以下是我的资源之一。

class Sites(Resource):
        def get(self, store):
            print('Received a request at ADDRESS for Store ' + store )
            conn = sqlite3.connect('store-db.db')
            cur = conn.cursor()
            res = cur.execute('SELECT * FROM Sites WHERE StoreNumber like ' + store)
            for r in res:
                if r == 'null':
                    return('No data', 404)
                else:
                    column_names = ["StoreNumber", "Street", "StreetSecondary","City","State", "ZipCode", "ContactNumber", "XO_TN", "RelocationStatus", "StoreType", "Timezone"]
                    data = [r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7], r[8], r[9], r[10]]            
                    datadict = {column_names[itemindex]:item for itemindex, item in enumerate(data)}
                    return(datadict, 200)

如果我向不存在的站点发出请求,则返回的值为null,但是我捕获此请求的尝试均未成功,因此我想知道我的检查方式是否不正确用Python?

我尝试r[0] == 'null'r is Noner == 'null'r == nullr == Null无济于事。

成功请求

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

{
  "StoreNumber": 42,
  "Street": "5000 Robinson Centre Drive",
  "StreetSecondary": "",
  "City": "Pittsburgh",
  "State": "PA",
  "ZipCode": "15205",
  "ContactNumber": "(412) 787-1330",
  "XO_TN": "(412) 249-9161",
  "RelocationStatus": "",
  "StoreType": "Dick's Sporting Goods",
  "Timezone": "Eastern"
}

没有数据的请求(应返回404)

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 15:11:41 GMT

null

1 个答案:

答案 0 :(得分:-2)

cur.rowcount()应该具有返回的行数。检查它是否大于0(无行)