【发布时间】:2019-04-29 12:59:24
【问题描述】:
现在我可以连接到 url api 和我的数据库。我正在尝试使用 psycopg2 将数据从 url 插入到 postgresql 数据库。我不完全理解如何做到这一点,这就是我能想到的。
import urllib3
import json
import certifi
import psycopg2
from psycopg2.extras import Json
http = urllib3.PoolManager(
cert_reqs='CERT_REQUIRED',
ca_certs=certifi.where())
url = '<API-URL>'
headers = urllib3.util.make_headers(basic_auth='<user>:<passowrd>')
r = http.request('GET', url, headers=headers)
data = json.loads(r.data.decode('utf-8'))
def insert_into_table(data):
for item in data['issues']:
item['id'] = Json(item['id'])
with psycopg2.connect(database='test3', user='<username>', password='<password>', host='localhost') as conn:
with conn.cursor() as cursor:
query = """
INSERT into
Countries
(revenue)
VALUES
(%(id)s);
"""
cursor.executemany(query, data)
conn.commit()
insert_into_table(data)
所以这段代码在cursor.executemany(query, data)上给我一个TypeError: string indices must be integers
所以我知道 json.loads 带回了一个类型对象,而 json.dumps 带回了一个类型字符串。我不确定我应该使用哪一个。而且我知道我完全错过了关于我如何定位“id”值并将其插入查询的内容。
还有一点关于 API,它非常庞大且复杂,最终我将不得不向下多棵树来获取某些值,这是我从中提取的一个示例。
我试图在“问题”而不是“问题类型”下获取“id”
{
"expand": "<>",
"startAt": 0,
"maxResults": 50,
"total": 13372,
"issues": [
{
"expand": "<>",
"id": "41508",
"self": "<>",
"key": "<>",
"fields": {
"issuetype": {
"self": "<>",
"id": "1",
"description": "<>",
"iconUrl": "<>",
"name": "<>",
"subtask": <>,
"avatarId": <>
},
【问题讨论】:
标签: python json python-3.x postgresql psycopg2