4 ms·
Any recommendations for an easy-to-use pg Python library? AFAICT psycopg2 requires users to do: import psycopg2 from psycopg2 import Error try:
by maest 5y ago
Any recommendations for an easy-to-use pg Python library? AFAICT psycopg2 requires users to do:
import psycopg2
from psycopg2 import Error
try:
# Connect to an existing database
connection = psycopg2.connect(user="postgres",
password="pynative@#29",
host="127.0.0.1",
port="5432",
database="postgres_db")
cursor = connection.cursor()
cursor.execute("SELECT version();")
record = cursor.fetchone()
Having to manage the connection object myself is meh.
I'd like to be able to do:
import pg_interface
pg = pg_interface.init(db_config)
pg.command(some_sql_string, some_params)
or even
import pg_interface
pg_interface.command(some_sql_string, some_params, db_config)
and have the lib deal with initialising and managing any connection pools/objects.
- ipmb 5y agohttps://www.encode.io/databases/ https://www.encode.io/databases/ maybe?
- throwawayboise 5y agoSo write those functions. Would be a minimal one-time investment that you could re-use everywhere.
- bb88 5y agoclass PG: _pg_conn = None @classmethod def pg(cls): if cls._pg_conn is None: cls._pg_conn = psycopg2.connect(...) return cls._pg_conn connection = PG.pg()
- steve-chavez 5y agoThere are python clients available[1]. For example with postgrest-py[2] you can do: async with PostgrestClient("http://<yourhost>.com") as client: r = await client.from_("countries").select("*").execute() countries = r.json() One advantage is that you don't have to worry about handling raw postgresql connections or pooling(as PostgREST does that for you), you only do HTTP requests. And if you want more complex SQL you can create functions or views. [1]: https://postgrest.org/en/v9.0/ecosystem.html#client-side-libraries https://postgrest.org/en/v9.0/ecosystem.html#client-side-lib... [2]: https://github.com/supabase-community/postgrest-py https://github.com/supabase-community/postgrest-py