最近在了解推荐系统的相关算法,在学习到一致性hash算法的时候,了解到,Python 已经有人造好轮子了,所以可以直接的使用,在使用的过程中,出现了一些错误,好在错误原因比较简单,解决的比较快,下面是错误解决方案:
如往常一样在linux
的已经激活的Python虚拟环境
上使用pip
安装相关库hash_ring
pip install hash_ring
在安装成功后,打开Python
,使用hash_ring
库
from hash_ring import *
然后报错:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/fanzhe/env/recommend/lib/python3.6/site-packages/hash_ring/__init__.py", line 5
except ImportError, e:
^
SyntaxError: invalid syntax
Python 老司机一眼就可以看出,这是Python2x的语法,到了Python3当然无法运行,但是我以为是安装出了问题,所以直接重装,小心翼翼的又重装了一次,当然咯,还是报错,于是可以判断出,是作者应该没有再更新这个库了,,,开始手动修改:
首先找到问题代码(/home/fanzhe/env/recommend/lib/python3.6/site-packages/hash_ring/__init__.py)
,并且打开如下:
from hash_ring import HashRing
try:
from memcache_ring import MemcacheRing
except ImportError,e:
pass
将其修改为Python3的语法:
from hash_ring import HashRing
try:
from memcache_ring import MemcacheRing
except ImportError as e:
pass
再次运行:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/fanzhe/env/recommend/lib/python3.6/site-packages/hash_ring/__init__.py", line 1, in <module>
from hash_ring import HashRing
ImportError: cannot import name 'HashRing'
什么鬼?没有模块,,,于是只好手动切换到目录(/home/fanzhe/env/recommend/lib/python3.6/site-packages/hash_ring/)
查看hash_ring.py
的内容:
明显可以看到,
hash_ring.py
下,是的确有HashRing
的,那么就只能是,索引不对啦,继续修改__init__.py
如下
from hash_ring.hash_ring import HashRing
try:
from memcache_ring import MemcacheRing
except ImportError as e:
pass
然后导入就没有问题了,开始使用,又发现新的问题:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/fanzhe/env/recommend/lib/python3.6/site-packages/hash_ring/hash_ring.py", line 62, in __init__
self._generate_circle()
File "/home/fanzhe/env/recommend/lib/python3.6/site-packages/hash_ring/hash_ring.py", line 79, in _generate_circle
for j in xrange(0, int(factor)):
NameError: name 'xrange' is not defined
看来要改的地方还很多啊,将所有2的语法升级到3后
"""
import math
import sys
from bisect import bisect
hash_ring
~~~~~~~~~~~~~~
Implements consistent hashing that can be used when
the number of server nodes can increase or decrease (like in memcached).
Consistent hashing is a scheme that provides a hash table functionality
in a way that the adding or removing of one slot
does not significantly change the mapping of keys to slots.
More information about consistent hashing can be read in these articles: