How to use the psycopg2.extras.RealDictCursor 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 p8ul / stackoverflow-lite / app / comments / models.py View on Github external
def save(self):
        """
        Insert a comment in comments table
        :return: True if record values are inserted successfully else false
        """
        con = psycopg2.connect(**self.config)
        cur = con.cursor(cursor_factory=RealDictCursor)
        try:
            query = "INSERT INTO comments(user_id, answer_id, comment_body) values(%s, %s, %s) "
            cur.execute(query, (session.get('user_id'), self.answer_id, self.comment_body))
            con.commit()
        except Exception as e:
            print(e)
            con.close()
            return False
        return True
github findopendata / findopendata / findopendata / metadata.py View on Github external
license_title = metadata["metadata"].get("license")
    license_url = None
    organization_display_name = metadata["resource"].get("attribution")
    organization_name = None
    organization_image_url = None
    organization_description = None

    # Package fields assigned
    crawler_table = "socrata_resources"
    original_host = domain
    num_files = 1

    # Get connection.
    conn = psycopg2.connect(**db_configs)
    # Get CKAN resources
    cur = conn.cursor(cursor_factory=RealDictCursor)

    # Save package
    cur.execute(r"""INSERT INTO findopendata.packages
            (
                crawler_table,
                crawler_key,
                id,
                original_host,
                num_files,
                created,
                modified,
                title,
                title_spacy,
                name,
                description,
                description_spacy,
github portfoliome / postpy / postpy / sql.py View on Github external
def select_dict(conn, query: str, params=None, name=None, itersize=5000):
    """Return a select statement's results as dictionary.

    Parameters
    ----------
    conn : database connection
    query : select query string
    params : query parameters.
    name : server side cursor name. defaults to client side.
    itersize : number of records fetched by server.
    """

    with conn.cursor(name, cursor_factory=RealDictCursor) as cursor:
        cursor.itersize = itersize
        cursor.execute(query, params)

        for result in cursor:
            yield result
github findopendata / findopendata / apiserver / main.py View on Github external
WHERE
                c.package_file_key = f.key
                AND f.package_key = p.key
                AND c.id IN %s
                AND p.original_host = h.original_host
    """
    if original_hosts:
        sql += r" AND p.original_host in %s "
        cur.execute(sql, (ids, original_hosts))
    else:
        cur.execute(sql, (ids,))


_original_hosts = []
cnx = cnxpool.getconn()
with cnx.cursor(cursor_factory=RealDictCursor) as cursor:
    cursor.execute(r"""SELECT
                    original_host,
                    display_name as original_host_display_name,
                    region as original_host_region
                FROM findopendata.original_hosts
                WHERE enabled
                ORDER BY display_name""")
    _original_hosts = [row for row in cursor.fetchall()]
cnxpool.putconn(cnx)


@app.route('/api/original-hosts', methods=['GET'])
def original_hosts():
    return jsonify(_original_hosts)

github antonnifo / StackOverflow-lite / app / api / v2 / questions / models.py View on Github external
def find_all(self):
        """method to find all questions"""
        query = """SELECT * from questions"""
        conn = self.db
        cursor = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
        cursor.execute(query)
        questions = cursor.fetchall()
        return questions
github codeforamerica / gotissues / gotissues / data_helpers.py View on Github external
def dict_cursor(conn, cursor_factory=extras.RealDictCursor):
    return conn.cursor(cursor_factory=cursor_factory)
github ProjectSidewalk / SidewalkWebpage / hit_creation.py View on Github external
# mTurk automatically appends worker and hit variables to the external url
    # Variable passed to the external url are workerid, assignmentid, hitid, ...
    # Once the task is successfully completed the external server needs to
    # perform a POST operation to an mturk url
    external_question = '' + \
        '' + url + '' + \
        str(frame_height) + ''

    # Get mturk client
    mturk = connect_to_mturk()

    try:
        # Connect to PostgreSQL database
        conn, engine = connect_to_db()

        cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)

        # Get all the current route_ids in  sidewalk.route
        cur.execute(
            """SELECT route_id, region_id from sidewalk.route order by street_count desc""")
        route_rows = cur.fetchall()
        routes = map(lambda x: x["route_id"], route_rows)

        t_before_creation = datetime.now()

        final_specific_routes = [55, 164, 220, 253, 342, 38, 460, 441, 411]
        # ignored_routes = [374, 206, 94, 346, 293, 139, 38, 53, 6, 225]
        # routes_for_gt = [38, 460, 441, 411]

        # For new route selection
        # specific_routes = []
        # for route_id in routes:
github Thurion / EDSM-RSE-for-EDMC / psycopg2 / extras.py View on Github external
def cursor(self, *args, **kwargs):
        kwargs.setdefault('cursor_factory', RealDictCursor)
        return super(RealDictConnection, self).cursor(*args, **kwargs)
github wellcometrust / reach / split_reach / web / app / db_storage.py View on Github external
def __init__(self, database_url):
        """Builds a connection object to the given PSQL database."""
        self.conn = psycopg2.connect(
            database_url,
            cursor_factory=RealDictCursor
        )
github kinabalu / mysticpaste / migrate_to_mongo.py View on Github external
#!/usr/bin/python
from pymongo import Connection
import psycopg2
import pprint
import psycopg2.extras

conn = psycopg2.connect("host=localhost dbname=mysticpaste")

cursor = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)

mongo = Connection()

cursor.execute("SELECT * FROM paste_items")

records = cursor.fetchall()

db = mongo.mysticpaste
collection = db.pastes
for record in records:
    n = {}
    if record['private_token']:
        n['itemId'] = record['private_token']
    else:
        n['itemId'] = str(record['item_id'])
    if record['content']: