代码之家  ›  专栏  ›  技术社区  ›  CodeSpent

为API构造JSON请求

  •  0
  • CodeSpent  · 技术社区  · 7 年前

    我正在构建一个小API,用于与其他项目的数据库交互。我已经建立了数据库,API运行良好,但是,我得到的数据并不是我想要的结构。

    我正在使用Python与 下面是处理交互的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)
    

    如果我向 /地点/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

    下面是一个我希望在向该端点发出请求后收到的示例:

    {
        "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 回复  |  直到 7 年前
        1
  •  1
  •   forgetso    7 年前

    您可以将列表转换为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
    

    我们现在有一个命名的dict,其中包含您的数据和列名。

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

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

    dict现在已转换为字符串。

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

    这不需要对数据库进行任何更改,但脚本需要了解列名或使用一些SQL动态检索列名。

    如果数据库中的数据格式正确,可以传递到前端,则不需要更改数据库结构。如果它的格式不正确,则可以更改它的存储方式,或者更改SQL查询以对其进行操作。

    推荐文章