當前位置: 首頁>>代碼示例>>Python>>正文


Python extras.Json方法代碼示例

本文整理匯總了Python中psycopg2.extras.Json方法的典型用法代碼示例。如果您正苦於以下問題:Python extras.Json方法的具體用法?Python extras.Json怎麽用?Python extras.Json使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在psycopg2.extras的用法示例。


在下文中一共展示了extras.Json方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: _serialize_event

# 需要導入模塊: from psycopg2 import extras [as 別名]
# 或者: from psycopg2.extras import Json [as 別名]
def _serialize_event(self, event):
        metadata = event.metadata
        doc = {'machine_serial_number': metadata.machine_serial_number,
               'event_type': event.event_type,
               'uuid': metadata.uuid,
               'index': metadata.index,
               'created_at': metadata.created_at}
        if metadata.request is not None:
            doc['user_agent'] = metadata.request.user_agent
            doc['ip'] = metadata.request.ip
            user = metadata.request.user
            if user:
                doc['user'] = Json(user.serialize())
        else:
            doc['user_agent'] = None
            doc['ip'] = None
            doc['user'] = None
        doc['payload'] = Json(event.payload)
        return doc 
開發者ID:zentralopensource,項目名稱:zentral,代碼行數:21,代碼來源:postgres.py

示例2: test_adapt_subclass

# 需要導入模塊: from psycopg2 import extras [as 別名]
# 或者: from psycopg2.extras import Json [as 別名]
def test_adapt_subclass(self):
        from psycopg2.extras import json, Json

        class DecimalEncoder(json.JSONEncoder):
            def default(self, obj):
                if isinstance(obj, Decimal):
                    return float(obj)
                return json.JSONEncoder.default(self, obj)

        class MyJson(Json):
            def dumps(self, obj):
                return json.dumps(obj, cls=DecimalEncoder)

        curs = self.conn.cursor()
        obj = Decimal('123.45')
        self.assertEqual(curs.mogrify("%s", (MyJson(obj),)),
            b("'123.45'")) 
開發者ID:synthetichealth,項目名稱:syntheticmass,代碼行數:19,代碼來源:test_types_extras.py

示例3: test_json

# 需要導入模塊: from psycopg2 import extras [as 別名]
# 或者: from psycopg2.extras import Json [as 別名]
def test_json(make_connection):
    conn = await make_connection()
    data = {'a': 1, 'b': 'str'}
    cur = await conn.cursor()
    try:
        await cur.execute("DROP TABLE IF EXISTS tbl")
        await cur.execute("""CREATE TABLE tbl (
                              id SERIAL,
                              val JSON)""")
        await cur.execute(
            "INSERT INTO tbl (val) VALUES (%s)", [Json(data)])
        await cur.execute("SELECT * FROM tbl")
        item = await cur.fetchone()
        assert (1, {'b': 'str', 'a': 1}) == item
    finally:
        cur.close() 
開發者ID:aio-libs,項目名稱:aiopg,代碼行數:18,代碼來源:test_extended_types.py

示例4: contains

# 需要導入模塊: from psycopg2 import extras [as 別名]
# 或者: from psycopg2.extras import Json [as 別名]
def contains(self, other):
        clone = self.as_json(True)
        if isinstance(other, (list, dict)):
            return Expression(clone, OP.JSONB_CONTAINS, Json(other))
        return Expression(clone, OP.JSONB_EXISTS, other) 
開發者ID:danielecook,項目名稱:Quiver-alfred,代碼行數:7,代碼來源:postgres_ext.py

示例5: __init__

# 需要導入模塊: from psycopg2 import extras [as 別名]
# 或者: from psycopg2.extras import Json [as 別名]
def __init__(self, dumps=None, *args, **kwargs):
        if Json is None:
            raise Exception('Your version of psycopg2 does not support JSON.')

        self.dumps = dumps
        super(JSONField, self).__init__(*args, **kwargs) 
開發者ID:danielecook,項目名稱:Quiver-alfred,代碼行數:8,代碼來源:postgres_ext.py

示例6: db_value

# 需要導入模塊: from psycopg2 import extras [as 別名]
# 或者: from psycopg2.extras import Json [as 別名]
def db_value(self, value):
        if value is None:
            return value
        if not isinstance(value, Json):
            return Json(value, dumps=self.dumps)
        return value 
開發者ID:danielecook,項目名稱:Quiver-alfred,代碼行數:8,代碼來源:postgres_ext.py

示例7: contained_by

# 需要導入模塊: from psycopg2 import extras [as 別名]
# 或者: from psycopg2.extras import Json [as 別名]
def contained_by(self, other):
        return Expression(self, OP.JSONB_CONTAINED_BY, Json(other)) 
開發者ID:danielecook,項目名稱:Quiver-alfred,代碼行數:4,代碼來源:postgres_ext.py

示例8: update_metadata

# 需要導入模塊: from psycopg2 import extras [as 別名]
# 或者: from psycopg2.extras import Json [as 別名]
def update_metadata(cls, table, column, srid, scale_x, scale_y, scale_z,
                        offset_x, offset_y, offset_z):
        '''
        Add an entry to the lopocs metadata tables to use.
        To be used after a fresh pc table creation.
        '''
        pcid = cls.query("""
            select pcid from pointcloud_columns
            where "schema" = %s and "table" = %s and "column" = %s
            """, (table.split('.')[0], table.split('.')[1], column)
        )[0][0]

        bbox = cls.compute_boundingbox(table, column)
        # compute bbox with offset and scale applied
        bbox_scaled = [0] * 6
        bbox_scaled[0] = (bbox['xmin'] - offset_x) / scale_x
        bbox_scaled[1] = (bbox['ymin'] - offset_y) / scale_y
        bbox_scaled[2] = (bbox['zmin'] - offset_z) / scale_z
        bbox_scaled[3] = (bbox['xmax'] - offset_x) / scale_x
        bbox_scaled[4] = (bbox['ymax'] - offset_y) / scale_y
        bbox_scaled[5] = (bbox['zmax'] - offset_z) / scale_z

        res = cls.query("""
            delete from pointcloud_lopocs where schematable = %s and "column" = %s;
            insert into pointcloud_lopocs (schematable, "column", srid, bbox)
            values (%s, %s, %s, %s) returning id
            """, (table, column, table, column, srid, bbox))
        plid = res[0][0]

        scales = scale_x, scale_y, scale_z
        offsets = offset_x, offset_y, offset_z

        json_schema = cls.patch2greyhoundschema(table, column)

        cls.execute("""
            insert into pointcloud_lopocs_outputs
            (id, pcid, scales, offsets, stored, bbox, point_schema)
            values (%s, %s, %s, %s, True, %s, %s)
        """, (
            plid, pcid, iterable2pgarray(scales), iterable2pgarray(offsets),
            iterable2pgarray(bbox_scaled), Json(json_schema))) 
開發者ID:Oslandia,項目名稱:lopocs,代碼行數:43,代碼來源:database.py

示例9: parse_committee_metadata

# 需要導入模塊: from psycopg2 import extras [as 別名]
# 或者: from psycopg2.extras import Json [as 別名]
def parse_committee_metadata(committee_metadata):
    id_ = committee_metadata['id']
    state = committee_metadata['state']
    chamber = committee_metadata['chamber']
    committee = committee_metadata['committee']
    subcommittee = committee_metadata['subcommittee']
    if len(committee_metadata['members']) > 0:
        members = Json(committee_metadata['members'][0])
    else: 
        members = None
    sources = committee_metadata['sources'][0]['url']
    parent_id = committee_metadata['parent_id']
    created_at = committee_metadata['created_at']
    updated_at = committee_metadata['updated_at']
    if len(committee_metadata['all_ids']) > 0:
        all_ids = committee_metadata['all_ids'][0]
    else:
        all_ids = None
    if 'level' in committee_metadata:
        level = committee_metadata['level']
    else:
        level = None

    return((id_, state, chamber, committee, subcommittee, members,
        sources, parent_id, created_at, updated_at, all_ids, level))



# GRAB COMMITTEE METADATA FROM FILES AND PUSH TO DATABASE 
開發者ID:dssg,項目名稱:policy_diffusion,代碼行數:31,代碼來源:committee_metadata.py

示例10: get_prep_value

# 需要導入模塊: from psycopg2 import extras [as 別名]
# 或者: from psycopg2.extras import Json [as 別名]
def get_prep_value(self, value):
        if value is not None:
            return Json(value)
        return value 
開發者ID:drexly,項目名稱:openhgsenti,代碼行數:6,代碼來源:jsonb.py

示例11: get_prep_lookup

# 需要導入模塊: from psycopg2 import extras [as 別名]
# 或者: from psycopg2.extras import Json [as 別名]
def get_prep_lookup(self, lookup_type, value):
        if lookup_type in ('has_key', 'has_keys', 'has_any_keys'):
            return value
        if isinstance(value, (dict, list)):
            return Json(value)
        return super(JSONField, self).get_prep_lookup(lookup_type, value) 
開發者ID:drexly,項目名稱:openhgsenti,代碼行數:8,代碼來源:jsonb.py

示例12: cleanup_tags

# 需要導入模塊: from psycopg2 import extras [as 別名]
# 或者: from psycopg2.extras import Json [as 別名]
def cleanup_tags(tags):
        """
        Delete tags because they have low accuracy or because they are in the
        blacklist. If no change is made, return None.
        :return: A SQL fragment if an update is required or None
        """
        update_required = False
        tag_output = []
        if not tags:
            return None
        for tag in tags:
            below_threshold = False
            if 'accuracy' in tag and tag['accuracy'] < TAG_MIN_CONFIDENCE:
                below_threshold = True
            if 'name' in tag:
                lower_tag = tag['name'].lower()
                should_filter = _tag_blacklisted(lower_tag) or below_threshold
            else:
                log.warning(f'Filtering malformed tag "{tag}" in "{tags}"')
                should_filter = True
            if should_filter:
                update_required = True
            else:
                tag_output.append(tag)

        if update_required:
            fragment = Json(tag_output)
            return fragment
        else:
            return None


# Define which tables, sources, and fields require cleanup. Map the field
# to a cleanup function that returns either a cleaned version of the field
# or 'None' to signal that no update is required. 
開發者ID:creativecommons,項目名稱:cccatalog-api,代碼行數:37,代碼來源:cleanup.py

示例13: test_tag_blacklist

# 需要導入模塊: from psycopg2 import extras [as 別名]
# 或者: from psycopg2.extras import Json [as 別名]
def test_tag_blacklist():
        tags = [
            {
                'name': 'cc0'
            },
            {
                'name': ' cc0'
            },
            {
                'name': 'valid',
                'accuracy': 0.99
            },
            {
                'name': 'valid_no_accuracy'
            },
            {
                'name': 'garbage:=metacrap',
            }
        ]
        result = str(CleanupFunctions.cleanup_tags(tags))
        expected = str(Json([
            {'name': 'valid', 'accuracy': 0.99},
            {'name': 'valid_no_accuracy'}
        ]))

        assert result == expected 
開發者ID:creativecommons,項目名稱:cccatalog-api,代碼行數:28,代碼來源:unit_tests.py

示例14: test_accuracy_filter

# 需要導入模塊: from psycopg2 import extras [as 別名]
# 或者: from psycopg2.extras import Json [as 別名]
def test_accuracy_filter():
        tags = [
            {
                'name': 'inaccurate',
                'accuracy': 0.5
            },
            {
                'name': 'accurate',
                'accuracy': 0.999
            }
        ]
        result = str(CleanupFunctions.cleanup_tags(tags))
        expected = str(Json([{'name': 'accurate', 'accuracy': 0.999}]))
        assert result == expected 
開發者ID:creativecommons,項目名稱:cccatalog-api,代碼行數:16,代碼來源:unit_tests.py

示例15: test_module_not_available

# 需要導入模塊: from psycopg2 import extras [as 別名]
# 或者: from psycopg2.extras import Json [as 別名]
def test_module_not_available(self):
        from psycopg2.extras import Json
        self.assertRaises(ImportError, Json(None).getquoted) 
開發者ID:synthetichealth,項目名稱:syntheticmass,代碼行數:5,代碼來源:test_types_extras.py


注:本文中的psycopg2.extras.Json方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。