Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/redis/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Redis在运行示例_Python_Redis - Fatal编程技术网

Python Redis在运行示例

Python Redis在运行示例,python,redis,Python,Redis,在我读的《Redis在行动》一书中,我看到了下面的例子,现在我想知道这是否正确。该示例具有以下python代码: def purchase_item(conn, buyerid, itemid, sellerid, lprice): buyer = "users:%s"%buyerid seller = "users:%s"%sellerid item = "%s.%s"%(itemid, sellerid) inventory = "inventory:%s"%buyerid end = ti

在我读的《Redis在行动》一书中,我看到了下面的例子,现在我想知道这是否正确。该示例具有以下python代码:

def purchase_item(conn, buyerid, itemid, sellerid, lprice):
buyer = "users:%s"%buyerid
seller = "users:%s"%sellerid
item = "%s.%s"%(itemid, sellerid)
inventory = "inventory:%s"%buyerid
end = time.time() + 10
pipe = conn.pipeline()


while time.time() < end:
    try:
        pipe.watch("market:", buyer)                #A
        price = pipe.zscore("market:", item)        #B
        funds = int(pipe.hget(buyer, "funds"))      #B
        if price != lprice or price > funds:        #B
            pipe.unwatch()                          #B
            return None


        pipe.multi()                                #C
        pipe.hincrby(seller, "funds", int(price))   #C
        pipe.hincrby(buyer, "funds", int(-price))   #C
        pipe.sadd(inventory, itemid)                #C
        pipe.zrem("market:", item)                  #C
        pipe.execute()                              #C
        return True
    except redis.exceptions.WatchError:             #D
        pass                                        #D


return False
def采购项目(conn、buyerid、itemid、sellerid、lprice):
买方=“用户:%s”%buyerid
seller=“用户:%s”%sellerid
item=“%s.%s”%(itemid,sellerid)
inventory=“库存:%s”%buyerid
结束=时间。时间()+10
管道=连接管道()
while time.time()基金:#B
管道未连接()
一无所获
管道。多个()#C
pipe.hincrby(卖方,“资金”,国际(价格))#C
pipe.hincrby(买方,“资金”,国际(-price))#C
管道sadd(库存,项目ID)#C
管道.zrem(“市场:,项目)#C
pipe.execute()#C
返回真值
除了redis.exceptions.WatchError:#D
及格
返回错误

正如您所看到的,这个示例使用管道,据我所知,在调用pipe.execute()之前,不会执行命令。在本例中,您在#B处看到一条if语句,但这里是否返回了price值?或者调用conn.pipeline()时,代码执行是否以某种方式被缓冲。

我假设您使用的是
redis py
库。调用
pipe.watch()
时,管道将立即进入执行模式。因此,您可以使用常规python代码检查后续命令的返回值。您可以使用
pipe.multi()
将管道再次置于缓冲模式,这正是代码所做的。最后一个
pipe.execute()
仅用于执行代码中标记为“#C”的命令。所有这些都在本文中进行了解释。总结如下:

pipe.watch(...) # <--- executed immediately
pipe.zscore(...) # <--- executed immediately
.....
pipe.multi() # <--- put pipeline back in *buffered* mode
pipe.incr(..) # <--- buffered command 1
pipe.incr(..) # <--- buffered command 2
pipe.execute() # <--- execute buffered commands 1 and 2
pipe.watch(…)#