Revision 4a105ce2 snf-pithos-backend/pithos/backends/random_word.py

b/snf-pithos-backend/pithos/backends/random_word.py
31 31
# interpreted as representing official policies, either expressed
32 32
# or implied, of GRNET S.A.
33 33

  
34
DEFAULT_ALPHABET = ('0123456789'
35
                    'abcdefghijklmnopqrstuvwxyz'
36
                    'ABCDEFGHIJKLMNOPQRSTUVWXYZ')
37
DEFAULT_MIN_LENGTH = 8
34
import random
38 35

  
39
from  random import randrange
40
from math import log
36
getrandbits = random.SystemRandom().getrandbits
41 37

  
42
def get_random_word(length=DEFAULT_MIN_LENGTH, alphabet=DEFAULT_ALPHABET):
43
    alphabet_length = len(alphabet)
44
    word = ''.join(alphabet[randrange(alphabet_length)]
45
        for _ in xrange(length))
46
    return word
38
DEFAULT_ALPHABET = ("0123456789"
39
                    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
40
                    "abcdefghijklmnopqrstuvwxyz")
47 41

  
48
def encode_serial(serial, alphabet=DEFAULT_ALPHABET):
49
    i = 0
42
def get_random_word(length, alphabet=DEFAULT_ALPHABET):
43
    remainder = getrandbits(length * 8)
44
    return encode_word(remainder, alphabet=alphabet)
45

  
46
def encode_word(number, alphabet=DEFAULT_ALPHABET):
50 47
    base = len(alphabet)
51
    quotient = int(serial)
52 48
    digits = []
53 49
    append = digits.append
54
    while quotient > 0:
50
    quotient = number
51
    while True:
55 52
        quotient, remainder = divmod(quotient, base)
56 53
        append(alphabet[remainder])
57
    word = ''.join(reversed(digits))
58
    return word
54
        if quotient <= 0:
55
            break
59 56

  
60
def get_word(serial, length=DEFAULT_MIN_LENGTH, alphabet=DEFAULT_ALPHABET):
61
    word = encode_serial(serial, alphabet)
62
    word += get_random_word(length, alphabet)
63
    return word
57
    return ''.join(digits)

Also available in: Unified diff