为了账号安全,请及时绑定邮箱和手机立即绑定

为 API 构建请求 JSON

为 API 构建请求 JSON

慕神8447489 2021-08-17 18:16:28
我正在构建一个小型 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"]以下是它在数据库中的结构: 最终,我想使用列名作为收到的 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 回答

?
Cats萌萌

TA贡献1805条经验 获得超9个赞

您可以将列表转换为 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 查询来操作它。


查看完整回答
反对 回复 2021-08-17
  • 1 回答
  • 0 关注
  • 174 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号