赞
踩
第一关
第二关
第三关(将代码文件全部替换即可)
#!/usr/bin/env python
#-*- coding:utf-8 -*-
import time
import redis
conn = redis.Redis()
# 将商品放到平台上
def add_item_to_market(itemid, sellerid, price):
# 请在下面完成要求的功能
#********* Begin *********#
repertory = "inventory:" + sellerid
item = itemid + "." + sellerid
end = time.time() + 5
pipe = conn.pipeline()
while time.time() < end:
try:
pipe.watch(repertory)
if not pipe.sismember(repertory, itemid):
pipe.unwatch()
return None
pipe.multi()
pipe.zadd("market", item, price)
pipe.srem(repertory, itemid)
pipe.execute()
return True
except redis.exceptions.WatchError:
pass
return False
#********* End *********#
# 购买商品
def purchase(buyerid, itemid):
# 请在下面完成要求的功能
#********* Begin *********#
item, sellerid = itemid.split(".")
buyer = "users:" + buyerid
seller = "users:" + sellerid
repertory = "inventory:" + buyerid
end = time.time() + 10
pipe = conn.pipeline()
while time.time() < end:
try:
pipe.watch("market", buyer)
price = pipe.zscore("market", itemid)
funds = int(pipe.hget(buyer, "funds"))
if funds < price:
pipe.unwatch()
return None
pipe.multi()
pipe.hincrby(seller, "funds", int(price))
pipe.hincrby(buyer, "funds", int(-price))
pipe.sadd(repertory, item)
pipe.zrem("market", itemid)
pipe.execute()
return True
except redis.exceptions.WatchError:
pass
return False
#********* End *********#
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。