Invalid connection option "cursorclass"

Hi folks, I’m trying to connect to an external Postres DB and following these docs:

https://anvil.works/docs/data-tables/external-database

import psycopg2
import psycopg2.extras

def connect():
  connection = psycopg2.connect(dbname='mydatabase',
                                host='db.example.com',
                                user='postgres',
                                password=anvil.secrets.get_secret('db_password'),
                                cursorclass=psycopg2.extras.RealDictCursor)

@anvil.server.callable
def get_people():
  conn = connect()
  with conn.cursor() as cur:
    cur.execute("SELECT name,date_of_birth,score FROM users")
    return cur.fetchall()

… and am getting

ProgrammingError: invalid dsn: invalid connection option "cursorclass" 

I’m following the code in the example verbatim as well as my own server module … same error.

Have no idea how to resolve this.

I think I’ve answered my own question. I believe the sample code from the docs is missing a few things.

connect()

needs to return the connection, and the RealDictCursor can be setup when the cursor in instantiated:

with conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor) as cur:

… now works.

3 Likes