为 API 构建请求 JSON

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


我使用 Python 和Flask/Flask-Restful作为 API。这是我处理交互的 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"

]

以下是它在数据库中的结构: 

http://img3.mukewang.com/611b8c9300010e0a10430102.jpg

最终,我想使用列名作为收到的 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)


慕神8447489
浏览 175回答 1
1回答

Cats萌萌

您可以将列表转换为 dict,然后在将其传回之前将其解析为 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)dict 现在已转换为字符串。'{"etc": "blah", "storeid": 42, "address": "1 the street"}'这不需要更改您的数据库,但脚本需要知道列名或使用某些 SQL 动态检索它们。如果数据库中的数据格式正确,可以传递给前端,那么您不需要更改数据库结构。如果它的格式不正确,那么您可以更改它的存储方式或更改您的 SQL 查询来操作它。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python