为API构建请求JSON

时间:2018-11-14 14:16:42

标签: python json rest sqlite

我正在构建一个小的API与其他项目的数据库交互。我已经建立了数据库并且API正常运行,但是,返回的数据并不是我想要的结构。

我正在将Python与 Flask / Flask-Restful 一起使用。 这是处理交互的Python片段:

class Address(Resource):
    def get(self, store):
        print('Received a request at ADDRESS for Store ' + store )
        conn = sqlite3.connect('store-db.db')
        cur = conn.cursor()
        addresses = cur.execute('SELECT * FROM Sites WHERE StoreNumber like ' + store)     
        for adr in addresses:
            return(adr, 200)

如果我向 / sites / 42 端点(其中 42 是站点ID)进行请求,那么我将收到以下消息:

[
    "42",
    "5000 Robinson Centre Drive",
    "",
    "Pittsburgh",
    "PA",
    "15205",
    "(412) 787-1330",
    "(412) 249-9161",
    "",
    "Dick's Sporting Goods"
]

在数据库中的结构如下: enter image description here

最终,我想将列名用作接收到的JSON中的键,但是我需要在正确的方向上进行一些指导,因此我不会在谷歌上寻找任何东西来寻找模棱两可的术语。

以下是我向该端点发出请求后希望收到的内容的示例:

{
    "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"
}

我只是想获得一些指导,以决定是否应该更改数据在数据库中的结构(即我已经看到一些只是将JSON放入其数据库中,但是我认为这很麻烦)或是否存在我可以用来控制数据的更直观的方法。

使用接受的答案更新代码

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

1 个答案:

答案 0 :(得分:1)

您可以将列表转换为字典,然后将其解析为JSON字符串,然后再传递回去。

// These are the names of the columns in your database
>>> column_names = ["storeid", "address", "etc"]

// This is the data coming from the database.
// All data is passed as you are using SELECT * in your query
>>> data = [42, "1 the street", "blah"]

// This is a quick notation for creating a dict from a list
// enumerate means we get a list index and a list item
// as the columns are in the same order as the data, we can use the list index to pull out the column_name
>>> datadict = {column_names[itemindex]:item for itemindex, item in enumerate(data)}

//This just prints datadict in my terminal
>>> datadict

我们现在有了一个包含您的数据和列名的命名字典。

{'etc': 'blah', 'storeid': 42, 'address': '1 the street'}

现在将datadict转储为字符串,以便可以将其发送到前端。

>>> import json
>>> json.dumps(datadict)

字典现已转换为字符串。

'{"etc": "blah", "storeid": 42, "address": "1 the street"}'

这不需要更改数据库,但是脚本将需要知道列名或使用某些SQL动态地检索它们。

如果数据库中的数据采用正确的格式以传递给前端,则您无需更改数据库结构。如果格式不正确,则可以更改其存储方式,也可以更改SQL查询以对其进行操作。