【问题标题】:How to send the output of Curl directly to a postgres databse如何将 Curl 的输出直接发送到 postgres 数据库
【发布时间】:2018-09-25 20:11:03
【问题描述】:

我想直接将输出发送到 postgres 数据库!有可能我必须先将其转换为另一种格式!任何的想法!!

curl -sG https://peeringdb.com/api/netixlan --data-urlencode asn=58717 \
  --data-urlencode fields=ix_id,ipaddr4,ipaddr6,speed | jq -c '.data[]'

输出是:

{"ix_id":215,"speed":1000,"ipaddr4":"198.32.167.102","ipaddr6":null} {"ix_id":158,"speed":10000,"ipaddr4":"27.111.228.8","ipaddr6":"2001:de8:4::5:8717:1"} {"ix_id":158,"speed":10000,"ipaddr4":"27.111.229.92","ipaddr6":"2001:de8:4::5:8717:2"} {"ix_id":429,"speed":10000,"ipaddr4":"103.16.102.35","ipaddr6":"2001:de8:12:100::35"}

【问题讨论】:

  • 你知道如何在postgres中插入数据吗?
  • 是的!我使用插入方法。我可以将输出发送到文本文件,然后将其发送回数据库,但我想直接将其发送到数据库。我试过 json 但我的 curl 有 | jq -c '.data[]' 对我来说不容易转换它
  • 我认为您可以使用 requests 库做您想做的事情。

标签: python json api postgresql-9.3 openstack-python-api


【解决方案1】:

您可以尝试使用 Pandas 和 sqlalchemy:

import pandas as pd
from sqlalchemy import create_engine

#Define your connection to the DB:
engine = create_engine('postgresql://username:password@servername:port/dbname')

#Convert your json to a Pandas Dataframe:
df = pd.read_json(json_file) # Your json goes here, 
     #or just create a dataframe from the curl dictionary output

#Sends the DataFrame to postgres:
df.to_sql('tablename', engine, if_exists='replace', schema='public')

【讨论】:

  • 就是你的意思!! df = pd.read_json(curl -sG peeringdb.com/api/netixlan --data-urlencode asn=58717 \ --data-urlencode fields=ix_id,ipaddr4,ipaddr6,speed | jq -c '.data[]')
  • 我的意思是你应该将你的 curl 命令输出到一个字符串(比如说 json_str),然后执行 df = pd.read_json(json_str)。您可以链接命令,但我并不完全熟悉具体细节。
  • 这实际上是我的问题!我无法将其转换为 json_str。因为 curl 有额外的参数,比如 | jq -c '.data[]'
猜你喜欢
  • 2014-02-06
  • 1970-01-01
  • 2022-01-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多