• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python extensions.adapt函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中psycopg2.extensions.adapt函数的典型用法代码示例。如果您正苦于以下问题:Python adapt函数的具体用法?Python adapt怎么用?Python adapt使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了adapt函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: updateRequest

    def updateRequest(self, team_id, requestDict):
        '''
        Method to a update a request in missions_request table
        @param team_id: team_id code e.g index in DB table of the team... as returned by rest api
        @param requestDict: request dictiionary - keys have to be the same key of Db
        '''
        self.checkConnection()
        
        # preare dictionary to be used for DB
        requestOdered = self.prepareRequestDict(team_id, requestDict)

        # create query
        sqlquery = "UPDATE missions_request SET "
        for k,v in requestOdered.items():
            if k == "id":
                continue
            sqlquery += '%s=%s, ' % (k,adapt(v))
        sqlquery = sqlquery[0:-2] + " "
        sqlquery += "WHERE id=%s" % adapt(requestOdered["id"])
        
        QgsLogger.debug(self.tr("Aggiorna request con la query: %s" % sqlquery), 1 )
        try:
            
            self.cursor.execute(sqlquery)
            
        except Exception as ex:
            raise(ex)
开发者ID:faunalia,项目名称:rt_geosisma_offline,代码行数:27,代码来源:ArchiveManager.py


示例2: updateTeam

    def updateTeam(self, teamDict):
        '''
        Method to a update a team in organization_team table
        @param teamDict: team dictiionary - keys have to be the same key of Db
        '''
        self.checkConnection()
        
        # preare dictionary to be used for DB
        teamOdered = self.prepareTeamDict(teamDict)

        # create query
        sqlquery = "UPDATE organization_team SET "
        for k,v in teamOdered.items():
            if k == "id":
                continue
            sqlquery += '%s=%s, ' % (k,adapt(v))
        sqlquery = sqlquery[0:-2] + " "
        sqlquery += "WHERE id=%s" % adapt(teamOdered["id"])
        
        QgsLogger.debug(self.tr("Aggiorna team con la query: %s" % sqlquery), 1 )
        try:
            
            self.cursor.execute(sqlquery)
            
        except Exception as ex:
            raise(ex)
开发者ID:faunalia,项目名称:rt_geosisma_offline,代码行数:26,代码来源:ArchiveManager.py


示例3: execute

    def execute(self, operation, parameters=None):

        if self.closed():
            raise errors.Error('Cursor is closed')

        if parameters:
            # optional requirement
            from psycopg2.extensions import adapt

            if isinstance(parameters, dict):
                for key in parameters:
                    v = adapt(parameters[key]).getquoted()
                    operation = operation.replace(':' + key, v)
            elif isinstance(parameters, tuple):
                operation = operation % tuple(adapt(p).getquoted() for p in parameters)
            else:
                raise errors.Error("Argument 'parameters' must be dict or tuple")

        self.rowcount = 0
        self.buffered_rows = collections.deque()
        self.last_execution = operation
        self.connection.write(messages.Query(operation))

        self.fetch_rows()

        if self.error is not None:
            raise self.error
开发者ID:carolssnz,项目名称:vertica-python,代码行数:27,代码来源:cursor.py


示例4: add_command

    def add_command(self,command):
        TAG = 'add_command'
        if isinstance(command, dict):
            if command.get(C.SAMSUNG_COMMANDS_TABLE_ACTION) and \
               command.get(C.SAMSUNG_COMMANDS_TABLE_DEVICE) \
                and command.get(C.SAMSUNG_COMMANDS_TABLE_UUID):

                if not command[C.SAMSUNG_COMMANDS_TABLE_ATTRIBUTE]:
                    command[C.SAMSUNG_COMMANDS_TABLE_ATTRIBUTE]= "{}"

                self.cursor.execute(""" insert into samsung_commands
                                    (device_id, action,attribute,command_uuid)
                                    values( %s,%s,%s,%s) returning id""",
                                    [command[C.SAMSUNG_COMMANDS_TABLE_DEVICE],
                                    command[C.SAMSUNG_COMMANDS_TABLE_ACTION],
                            adapt(command[C.SAMSUNG_COMMANDS_TABLE_ATTRIBUTE]),
                            adapt(command[C.SAMSUNG_COMMANDS_TABLE_UUID])])

                if self.cursor.rowcount>0:
                    row = self.cursor.fetchone();
                    return row[0]
                else:
                    return None
        else:
            self.log.i(TAG, 'Not all required parameters sent in '+command.__repr__())
            return None
开发者ID:aman-gautam,项目名称:mv-server,代码行数:26,代码来源:samsung_command.py


示例5: adapt_box

def adapt_box(box):
    return AsIs("'(%s,%s),(%s,%s)'::box" % (
        adapt(box.first_vertex.x),
        adapt(box.first_vertex.y),
        adapt(box.second_vertex.x),
        adapt(box.second_vertex.y)
    ))
开发者ID:EnTeQuAk,项目名称:django-orm,代码行数:7,代码来源:objects.py


示例6: add_device

    def add_device(self, device):
        TAG = 'add_device'

        ## if user_id, udid and os is present then only we can do entry
        if type(device) == dict and C.DEVICE_TABLE_USER in device:

            if UserDBHelper().is_user_valid(str(device.get('user_id'))):
                if device.has_key(C.DEVICE_TABLE_OS):
                    if device.has_key(C.DEVICE_TABLE_UDID):
                        try:
                            self.cursor.execute("""INSERT INTO devices
                               (os, udid, user_id) VALUES({0}, {1}, {2})
                               RETURNING id""".format(adapt(device.get('os')),
                                 adapt(device.get('udid')),
                                  adapt(device.get('user_id'))))

                        except Exception,err:
                            self.log.e(TAG,'Exception : ' + repr(err))
                            return None
                        if self.cursor.rowcount > 0:
                            row = self.cursor.fetchone()
                            return row[0]
                        else:
                            self.log.e(TAG,'Not abe to insert in device table')
                            return None
                    else:
                        self.log.e(TAG,'UDID not found in dictionary')
                        return None
                else:
                    self.log.e(TAG, 'OS is not found in dictionary')
                    return None
            else:
                self.log.e(TAG, 'USER ID not found in dictionary')
                return None
开发者ID:aman-gautam,项目名称:mv-server,代码行数:34,代码来源:device.py


示例7: getquoted

    def getquoted(self):
        if self.name is None:
            raise NotImplementedError(
                "RangeAdapter must be subclassed overriding its name " "or the getquoted() method"
            )

        r = self.adapted
        if r.isempty:
            return b("'empty'::" + self.name)

        if r.lower is not None:
            a = adapt(r.lower)
            if hasattr(a, "prepare"):
                a.prepare(self._conn)
            lower = a.getquoted()
        else:
            lower = b("NULL")

        if r.upper is not None:
            a = adapt(r.upper)
            if hasattr(a, "prepare"):
                a.prepare(self._conn)
            upper = a.getquoted()
        else:
            upper = b("NULL")

        return b(self.name + "(") + lower + b(", ") + upper + b(", '%s')" % r._bounds)
开发者ID:MNI-NIL,项目名称:NIL-MNI.github.io,代码行数:27,代码来源:_range.py


示例8: adapt_lseg

def adapt_lseg(l):
    return AsIs("'[(%s,%s), (%s,%s)]'::lseg" % (\
        adapt(l.init_point.x),
        adapt(l.init_point.y),
        adapt(l.end_point.x),
        adapt(l.end_point.y)
    ))
开发者ID:EnTeQuAk,项目名称:django-orm,代码行数:7,代码来源:objects.py


示例9: adapt_range

def adapt_range(pgrange, pyrange):
    if isinstance(pgrange, ustr):
        pgrange = pgrange.encode("utf8")

    if not isinstance(pyrange, range_):
        raise ValueError((
            "Trying to adapt range {range.__class__.__name__} which does not "
            "extend base range type.").format(range=pyrange))

    if not pyrange:
        return AsIs((b"'empty'::" + pgrange).decode("utf8"))

    lower = b"NULL"
    if not pyrange.lower_inf:
        lower = adapt(pyrange.lower).getquoted()

    upper = b"NULL"
    if not pyrange.upper_inf:
        upper = adapt(pyrange.upper).getquoted()

    return AsIs(b"".join([
        pgrange,
        b"(",
        lower,
        b", ",
        upper,
        b", '",
        b"[" if pyrange.lower_inc else b"(",
        b"]" if pyrange.upper_inc else b")",
        b"')",
    ]).decode("utf8"))
开发者ID:runfalk,项目名称:psycospans,代码行数:31,代码来源:_utils.py


示例10: adapt_box

def adapt_box(box):
    return AsIs("'(%s,%s),(%s,%s)'::box" % (
        adapt(box.init_point.x),
        adapt(box.init_point.y),
        adapt(box.end_point.x),
        adapt(box.end_point.y)
    ))
开发者ID:Locu,项目名称:django-orm-extensions,代码行数:7,代码来源:adapt.py


示例11: topologyInsert

def topologyInsert(con, simulationId, atomNum, atomName, atomType, residueCode, residueNumber, chainCode, description):
    sql_insert_topology="INSERT INTO dnamodel.topology (simulationId, atomNum, atomName, atomType, residueNum, residueCode, chainCode, description) VALUES (%s, %s, %s, %s, %s, %s, %s, %s) RETURNING topologyId;"
    cur = con.cursor()
    cur.execute(sql_insert_topology, (simulationId, atomNum, adapt(atomName), adapt(atomType), residueNumber, adapt(residueCode), adapt(chainCode), adapt(description)))
    topologyId = cur.fetchone()[0]
    cur.close()
    return topologyId
开发者ID:PauAndrio,项目名称:PostgreDnaLoader,代码行数:7,代码来源:dnamodelLoader_withCopy.py


示例12: getquoted

    def getquoted(self):
        if self.name is None:
            raise NotImplementedError(
                "RangeAdapter must be subclassed overriding its name " "or the getquoted() method"
            )

        r = self.adapted
        if r.isempty:
            return b"'empty'::" + self.name.encode("utf8")

        if r.lower is not None:
            a = adapt(r.lower)
            if hasattr(a, "prepare"):
                a.prepare(self._conn)
            lower = a.getquoted()
        else:
            lower = b"NULL"

        if r.upper is not None:
            a = adapt(r.upper)
            if hasattr(a, "prepare"):
                a.prepare(self._conn)
            upper = a.getquoted()
        else:
            upper = b"NULL"

        return self.name.encode("utf8") + b"(" + lower + b", " + upper + b", '" + r._bounds.encode("utf8") + b"')"
开发者ID:psycopg,项目名称:psycopg2,代码行数:27,代码来源:_range.py


示例13: adapt_range

def adapt_range(pgrange, pyrange):
    if not isinstance(pyrange, range_):
        raise ValueError((
            "Trying to adapt range {range.__class__.__name__} which does not "
            "extend base range type.").format(range=pyrange))

    if not pyrange:
        return AsIs("'empty'::" + pgrange)

    lower = b("NULL")
    if not pyrange.lower_inf:
        lower = adapt(pyrange.lower).getquoted()

    upper = b("NULL")
    if not pyrange.upper_inf:
        upper = adapt(pyrange.upper).getquoted()

    return AsIs(b"".join([
        b(pgrange),
        b("("),
        lower,
        b(", "),
        upper,
        b(", '"),
        b("[" if pyrange.lower_inc else "("),
        b("]" if pyrange.upper_inc else ")"),
        b("')")
    ]).decode("utf8"))
开发者ID:pombredanne,项目名称:psycospans,代码行数:28,代码来源:_utils.py


示例14: getquoted

    def getquoted(self):
        if self.name is None:
            raise NotImplementedError(
                'RangeAdapter must be subclassed overriding its name '
                'or the getquoted() method')

        r = self.adapted
        if r.isempty:
            return b"'empty'::" + self.name.encode('utf8')

        if r.lower is not None:
            a = adapt(r.lower)
            if hasattr(a, 'prepare'):
                a.prepare(self._conn)
            lower = a.getquoted()
        else:
            lower = b'NULL'

        if r.upper is not None:
            a = adapt(r.upper)
            if hasattr(a, 'prepare'):
                a.prepare(self._conn)
            upper = a.getquoted()
        else:
            upper = b'NULL'

        return self.name.encode('utf8') + b'(' + lower + b', ' + upper \
            + b", '" + r._bounds.encode('utf8') + b"')"
开发者ID:CollinsMuiruri,项目名称:Instagram,代码行数:28,代码来源:_range.py


示例15: getSingleTableSql

def getSingleTableSql(host, name, interval=None):
    if interval==None:
        interval = "AND tsd_timestamp > ('now'::timestamp - '8 days'::interval)"
    else:
        if 'interval' in interval:
            interval = "AND tsd_timestamp > %s::interval" % (adapt(interval['interval']), )
        else:
            interval = "AND tsd_timestamp BETWEEN %s::timestamp and %s::timestamp" % (adapt(interval['from']),adapt(interval['to']), )

    sql = """
    SELECT tsd_table_id,
           tsd_timestamp,
           tsd_table_size,
           tsd_index_size,
           tsd_seq_scans,
           tsd_index_scans,
           tsd_tup_ins,
           tsd_tup_upd,
           tsd_tup_del,
           tsd_tup_hot_upd
      FROM monitor_data.table_size_data
     WHERE tsd_table_id = ( SELECT t_id FROM monitor_data.tables WHERE t_schema || '.' || t_name = """ + str(adapt(name)) + """ AND t_host_id = """ + str(adapt(host)) + """ )
       AND tsd_host_id = """ + str(adapt(host)) + """
       """+interval+"""
      ORDER BY tsd_timestamp ASC
    """

    return sql
开发者ID:emrul,项目名称:PGObserver,代码行数:28,代码来源:tabledata.py


示例16: getquoted

 def getquoted(self):
     r = []
     for k in self.attnames:
        if self.adapted.has_key(k):
           r.append(adapt(self.adapted[k]))
        else:
           r.append(None)
     return adapt(r)
开发者ID:luodaobin,项目名称:scratchbox,代码行数:8,代码来源:pgutil.py


示例17: test_adapt_subtype

    def test_adapt_subtype(self):
        from psycopg2.extensions import adapt

        class Sub(str):
            pass
        s1 = "hel'lo"
        s2 = Sub(s1)
        self.assertEqual(adapt(s1).getquoted(), adapt(s2).getquoted())
开发者ID:gencer,项目名称:psycopg2,代码行数:8,代码来源:test_types_basic.py


示例18: snmpResult2RRD2

def snmpResult2RRD2(host):
    connection = psycopg2.connect(
                host='10.0.10.111', port=54321, database='GIS_2010',
                user='macswriter', password='macswriter'
            )

    cursor = connection.cursor()

    dOid_to_Res = dict()

    for i, o in enumerate(host.oids):
        dOid_to_Res[o] = host.results[i]

    data = {}

    for oid, results in dOid_to_Res.items():
        for port, result in results.items():
            if data.get(port, None):
                data[port][oid.name] = int(result)
            else:
                data[port] = { oid.name: int(result) }


    for port, values in data.items():
        insert = "INSERT INTO netstats.traf (%s) VALUES (%s)"
        query = insert % (
                            ', '.join([ '"%s"' % col for col in
                                    ['dev_name', 'port'] \
                                    + values.keys() \
                                    + ['inserted',]
                                ]),
                            ', '.join(
                                    [adapt(host.hostname).getquoted(), str(port)] \
                                    + [str(adapt(v)) for v in values.values()] \
                                    # + ['now()',]
                                    + ["'%s'" % datetime.now(),]
                                )
                        )
        cursor.execute(query)
        # print query

    connection.commit()
    cursor.close()
    connection.close()

    rrdbase = '%s/%s'  % (host.hostdir, host.perfbase)
    updstr = 'N:%s:%s' % (host.snmptime, host.errors)
    #sys.stderr.write('%s, %s\n' % (rrdbase, updstr))
    #sys.stderr.flush()

    try:
        rrdtool.update(rrdbase, updstr) 
    except Exception, why:
        print "Error in update (%s, %s) - %s" % (
                            host.hostname,
                            index,
                            why )
开发者ID:brownian,项目名称:SPyBG,代码行数:57,代码来源:snmpResult2RRD.py


示例19: on_get

    def on_get(self, req, resp):
        '''Return json object related to GET with lat & lon HTTP parameters
        '''
        
        raw_lat = req.get_param('lat')
        raw_lon = req.get_param('lon')
        if raw_lat is None or raw_lon is None:
            resp.status = falcon.HTTP_400
            lat = None
            lon = None
        else:
            lat = decimal.Decimal(raw_lat)
            lon = decimal.Decimal(raw_lon)
        
        if not (self.lat_is_valid(lat) and self.lon_is_valid(lon)):
            resp.status = falcon.HTTP_400
        else:
            dbc = db.connect()
            cur = dbc.cursor()
            
            nb_maps_raw = req.get_param('nb_maps')
            nb_addr_raw = req.get_param('nb_addr')
            if nb_maps_raw is None:
                nb_maps_raw = '20'
            if nb_addr_raw is None:
                nb_addr_raw = '10'
            nb_maps = decimal.Decimal(nb_maps_raw)
            nb_addr = decimal.Decimal(nb_addr_raw)

            #id (uuid), path (str), geom (geom), address (str), level (str), building (str)
            loc = "st_setsrid(st_makepoint(%s,%s),4326)" % (lon,lat)
            query = """SELECT array_to_json(array_agg(row_to_json(t)))::text FROM (
              SELECT floor(st_distance(geom::geography, %s::geography)) as dist,
                     ST_X(geom) as lon, ST_Y(geom) as lat, * FROM (
                 (select * from ban_nomap where ST_DWithin(geom, %s, 0.001) order by st_distance(geom,%s) limit %s)
                 union
                 (select * from map_info where ST_DWithin(geom, %s, 0.1) limit %s)) as d ORDER BY ST_Distance(geom,%s), level) t
            """ % (loc, loc,loc,adapt(nb_addr),loc,adapt(nb_maps),loc)
            cur.execute(query)
            what_is_around = cur.fetchone()[0]

            
            resp.set_header('X-Powered-By', 'OpenEvacMap')
            if what_is_around is None:
                resp.status = falcon.HTTP_204
            else:
                resp.status = falcon.HTTP_200
                resp.set_header('Access-Control-Allow-Origin', '*')
                resp.set_header('Access-Control-Allow-Headers', 'X-Requested-With')
                resp.body = (what_is_around)

                query = """INSERT INTO log (loc, ip) VALUES (ST_SetSRID(ST_GeometryFromText('POINT(%s %s)'),4326),'%s');""" % (lon,lat,req.env['REMOTE_ADDR'])
                cur.execute(query)
                dbc.commit()

            cur.close()
            dbc.close()
开发者ID:openevacmap,项目名称:openevac-back,代码行数:57,代码来源:mapinfo.py


示例20: prepare_select_processes

def prepare_select_processes(server_url, identifier):
    return (
        "SELECT id FROM " + tables["processes"] + " "
        "WHERE wps_server_id IN ("
                "SELECT id FROM " + tables["wpsServers"] + " "
                "WHERE url = " + str(adapt(server_url)) + " "
            ")"
            "AND identifier = "  + str(adapt(identifier))    
    )
开发者ID:ERIN-LIST,项目名称:iguess,代码行数:9,代码来源:harvester.py



注:本文中的psycopg2.extensions.adapt函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python extensions.b函数代码示例发布时间:2022-05-25
下一篇:
Python errorcodes.lookup函数代码示例发布时间:2022-05-25
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap