How to use the psycopg2.extras.DictCursor function in psycopg2

To help you get started, we’ve selected a few psycopg2 examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github psycopg / psycopg2 / tests / test_extras_dictcursor.py View on Github external
def test_order_iter(self):
        curs = self.conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
        curs.execute("select 5 as foo, 4 as bar, 33 as baz, 2 as qux")
        r = curs.fetchone()
        self.assertEqual(list(r.iterkeys()), ['foo', 'bar', 'baz', 'qux'])
        self.assertEqual(list(r.itervalues()), [5, 4, 33, 2])
        self.assertEqual(list(r.iteritems()),
            [('foo', 5), ('bar', 4), ('baz', 33), ('qux', 2)])

        r1 = pickle.loads(pickle.dumps(r))
        self.assertEqual(list(r1.iterkeys()), list(r.iterkeys()))
        self.assertEqual(list(r1.itervalues()), list(r.itervalues()))
        self.assertEqual(list(r1.iteritems()), list(r.iteritems()))
github aartur / mschematool / tests / test_basic.py View on Github external
def cursor(self):
        import psycopg2.extras
        return self.conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
github aamks / aamks / include.py View on Github external
def __init__(self):

        import psycopg2
        import psycopg2.extras

        self._project_name=os.path.basename(os.environ['AAMKS_PROJECT'])
        try:
            self.PSQL=psycopg2.connect("dbname='aamks' user='aamks' host='127.0.0.1' password='{}'".format(os.environ['AAMKS_PG_PASS']))
            self.psqldb=self.PSQL.cursor(cursor_factory=psycopg2.extras.DictCursor)
        except:
            raise SystemExit("Fatal: Cannot connect to postresql.")
github Uninett / nav / python / nav / web / geomap / views.py View on Github external
def data(request, variant):
    """Respond to a data request.

    GET paramaters in the request object specify the bounding box of
    the area to retrieve data for and other parameters.

    variant must be a variant name defined in the configuration file.

    """
    connection = nav.db.getConnection('geomapserver', 'manage')
    connection.set_isolation_level(1)
    db = connection.cursor(cursor_factory=psycopg2.extras.DictCursor)

    truthy = ['True', 'true', True]
    do_create_edges = request.GET.get('create_edges', True) in truthy
    do_fetch_data = request.GET.get('fetch_data', True) in truthy
    format_ = request.GET['format']
    if 'bbox' in request.GET:
        bbox = request.GET['bbox']
        bounds = {}
        (bounds['minLon'], bounds['minLat'],
         bounds['maxLon'], bounds['maxLat']) = map(float, bbox.split(','))
    else:
        bounds = {'minLon': float(request.GET['minLon']),
                  'maxLon': float(request.GET['maxLon']),
                  'minLat': float(request.GET['minLat']),
                  'maxLat': float(request.GET['maxLat'])}
    viewport_size = {'width': int(request.GET['viewportWidth']),
github ayr-ton / kamu / books / management / commands / migrate_kamu.py View on Github external
def handle(self, *args, **options):
        self.connection = psycopg2.connect("dbname='%s'" % options['database'])
        self.cursor = self.connection.cursor(cursor_factory = psycopg2.extras.DictCursor)
        self.migrate_books()
        self.migrate_libraries()
        self.migrate_copies()
        self.migrate_users()
        self.migrate_loans()
github kashifrazzaqui / vyked / vyked / sql.py View on Github external
def get_cursor(cls, cursor_type=_CursorType.PLAIN) -> Cursor:
        """
        Yields:
            new client-side cursor from existing db connection pool
        """
        pool = yield from cls.get_pool()
        if cursor_type == _CursorType.PLAIN:
            c = yield from pool.cursor()
            return c
        if cursor_type == _CursorType.NAMEDTUPLE:
            return (yield from pool.cursor(cursor_factory=psycopg2.extras.NamedTupleCursor))
        if cursor_type == _CursorType.DICT:
            return (yield from pool.cursor(cursor_factory=psycopg2.extras.DictCursor))
github akrherz / iem / scripts / ingestors / madis / to_iemaccess.py View on Github external
def main():
    """Do Something"""
    pgconn = get_dbconn("iem")
    icursor = pgconn.cursor(cursor_factory=psycopg2.extras.DictCursor)
    fn = find_file()
    nc = ncopen(fn, timeout=300)

    stations = chartostring(nc.variables["stationId"][:])
    providers = chartostring(nc.variables["dataProvider"][:])
    names = chartostring(nc.variables["stationName"][:])

    tmpk = nc.variables["temperature"][:]
    dwpk = nc.variables["dewpoint"][:]
    relh = nc.variables["relHumidity"][:]

    # Set some data bounds to keep mcalc from complaining
    tmpk = np.where(
        np.ma.logical_or(np.ma.less(tmpk, 200), np.ma.greater(tmpk, 320)),
        np.nan,
        tmpk,
github ansible / ansible / lib / ansible / modules / database / postgresql / postgresql_user.py View on Github external
privs = parse_privs(module.params["priv"], module.params["db"])
    no_password_changes = module.params["no_password_changes"]
    if module.params["encrypted"]:
        encrypted = "ENCRYPTED"
    else:
        encrypted = "UNENCRYPTED"
    expires = module.params["expires"]
    conn_limit = module.params["conn_limit"]
    role_attr_flags = module.params["role_attr_flags"]
    groups = module.params["groups"]
    if groups:
        groups = [e.strip() for e in groups]

    conn_params = get_conn_params(module, module.params, warn_db_default=False)
    db_connection = connect_to_db(module, conn_params)
    cursor = db_connection.cursor(cursor_factory=DictCursor)

    try:
        role_attr_flags = parse_role_attrs(cursor, role_attr_flags)
    except InvalidFlagsError as e:
        module.fail_json(msg=to_native(e), exception=traceback.format_exc())

    kw = dict(user=user)
    changed = False
    user_removed = False

    if state == "present":
        if user_exists(cursor, user):
            try:
                changed = user_alter(db_connection, module, user, password,
                                     role_attr_flags, encrypted, expires, no_password_changes, conn_limit)
            except SQLParseError as e:
github ansible / ansible / lib / ansible / modules / extras / database / postgresql / postgresql_ext.py View on Github external
"login_password":"password",
        "port":"port"
    }
    kw = dict( (params_map[k], v) for (k, v) in module.params.iteritems() 
              if k in params_map and v != '' )
    try:
        db_connection = psycopg2.connect(database=db, **kw)
        # Enable autocommit so we can create databases
        if psycopg2.__version__ >= '2.4.2':
            db_connection.autocommit = True
        else:
            db_connection.set_isolation_level(psycopg2
                                              .extensions
                                              .ISOLATION_LEVEL_AUTOCOMMIT)
        cursor = db_connection.cursor(
                cursor_factory=psycopg2.extras.DictCursor)
    except Exception:
        e = get_exception()
        module.fail_json(msg="unable to connect to database: %s" % e)

    try:
        if module.check_mode:
            if state == "present":
                changed = not ext_exists(cursor, ext)
            elif state == "absent":
                changed = ext_exists(cursor, ext)
        else:
            if state == "absent":
                changed = ext_delete(cursor, ext)
    
            elif state == "present":
                changed = ext_create(cursor, ext)
github akrherz / iem / htdocs / plotting / auto / scripts / p48.py View on Github external
def plotter(fdict):
    """ Go """
    pgconn = get_dbconn("postgis")
    cursor = pgconn.cursor(cursor_factory=psycopg2.extras.DictCursor)
    ctx = get_autoplot_context(fdict, get_description())

    ugc = ctx["ugc"]
    phenomena = ctx["phenomena"]
    significance = ctx["significance"]

    (fig, ax) = plt.subplots(1, 1, figsize=(8, 6))

    cursor.execute(
        """
    SELECT s.wfo, s.tzname, u.name from ugcs u
    JOIN stations s on (u.wfo = s.id)
    where ugc = %s and end_ts is null and s.network = 'WFO'
    """,
        (ugc,),
    )