我有一个python API,它可以访问URL并接收JSON。有一个包含订单数据的表
Order_id ZipCode delivery_date total
API返回的json包含传递的zipcode的城市和状态。
我想:
City and State
如何通过python完成?
答案 0 :(得分:0)
您可以使用适配器建立与python的连接,如psycopg2或sqlalchemy
使用psycopg2
import psycopg2
class Postgres(object):
"""docstring for Postgres"""
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = object.__new__(cls)
# normally the db_credenials would be fetched from a config file or the enviroment
# meaning shouldn't be hardcoded as follow
db_config = {'dbname': 'demo', 'host': 'localhost',
'password': 'postgres', 'port': 5432, 'user': 'postgres'}
try:
print('connecting to PostgreSQL database...')
connection = Postgres._instance.connection =
psycopg2.connect(**db_config)
cursor = Postgres._instance.cursor = connection.cursor()
cursor.execute('SELECT VERSION()')
db_version = cursor.fetchone()
except Exception as error:
print('Error: connection not established {}'.format(error))
Postgres._instance = None
else:
print('connection established\n{}'.format(db_version[0]))
return cls._instance
def __init__(self):
self.connection = self._instance.connection
self.cursor = self._instance.cursor
def write(self, query):
try:
self.cursor.execute(query)
except Exception as error:
print('error execting query "{}", error: {}'.format(query, error))
return None
def read(self, query):
try:
self.cursor.execute(query)
return self.cursor.fetchall()
except Exception as error:
print('error execting query "{}", error: {}'.format(query, error))
return None
else:
return result
def __del__(self):
self.connection.close()
self.cursor.close()
然后实例化类postgress,并调用方法读取或写入,如果目标是从数据库写入或读取。