开发者

Python short url generator

I'm using this code to generate short url. http://code.activestate.com/recipes/576918/

The idea is to encode an integer id using base62 and function enbase just works fine.

开发者_如何学JAVAclass UrlEncoder(object):
    ...
    def enbase(self, x, min_length=0):
        result = self._enbase(x)
        padding = self.alphabet[0] * (min_length - len(result))
        return '%s%s' % (padding, result)

But I don't quite understand what this code is for:

class UrlEncoder(object):
    ...

    def encode_url(self, n, min_length=0):
        return self.enbase(self.encode(n), min_length)
    def decode_url(self, n):
        return self.decode(self.debase(n))
    def encode(self, n):
        return (n & ~self.mask) | self._encode(n & self.mask)

Why encode then enbase? What does that bitwise operation do? Could someone shed some light on me? Thanks.


Looking at the whole code: The net effect of encode() is to apply _encode() to the least-significant self.block_size-many bits of the value. _encode() appears to reverse those bits. It seems to be just a bit of additional scrambling. The documentation below the code explains why they are doing all these extra shuffles.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜