使用for循环的结果dict填充数据库-Psycopg2

时间:2019-07-13 11:26:56

标签: python json postgresql python-requests psycopg2

我有这个简单的测试例程,可以将一些数据插入到我的数据库中:

import psycopg2

    try:
       connection = psycopg2.connect(user="postgres",
                                  password="mypassword",
                                  host="127.0.0.1",
                                  port="5432",
                                  database="myjson_db")
       cursor = connection.cursor()

       postgres_insert_query = """ INSERT INTO myjson_db (LENGTH, WAREHOUSE, COST) VALUES (%s,%s,%s)"""
       record_to_insert = (1.600, 2.0, 50000000)
       cursor.execute(postgres_insert_query, record_to_insert)
       connection.commit()
       count = cursor.rowcount
       print (count, "Record inserted successfully into myjson table")
    except (Exception, psycopg2.Error) as error :
        if(connection):
            print("Failed to insert record into myjson table", error)
    finally:
        if(connection):
            cursor.close()
            connection.close()
            print("PostgreSQL connection is closed")

这实际上有效,但是我感到困惑,因为我真正需要的是将API的结果插入其中(它是json,但是我设法提取了所需的数据)

例如,这是我的API脚本:

import requests

response = requests.get("https://url/api/object/")
data = response.json()
for object in data['results']:
    print(object['length'])

while data['next'] is not None:
    response = requests.get(data['next'])
    data = response.json()
    for object in data['results']:
        print(object['warehouse'])

因此,此脚本连接到api,读取分页的json响应,然后在该响应上循环,以打印所需的特定“字段”。

现在,如何将结果存储到我的postgres db表中?

是否存在“动态”方式将请求脚本与psycopg2例程集成?像我正在做的那样“打印”但直接发送到数据库?

还是应该以不同的心态来对待这个问题?

请注意,我无法使用json postgres字段,我确实为此表指定了一些行,例如warehouselength

您是否可以提供类似的示例?

0 个答案:

没有答案