__init__.py 761 B

123456789101112131415161718192021222324252627282930
  1. # coding=utf-8
  2. from __future__ import unicode_literals
  3. from .. import BaseProvider
  4. class Provider(BaseProvider):
  5. def ean(self, length=13):
  6. code = [self.random_digit() for _ in range(length - 1)]
  7. if length not in (8, 13):
  8. raise AssertionError("length can only be 8 or 13")
  9. if length == 8:
  10. weights = [3, 1, 3, 1, 3, 1, 3]
  11. elif length == 13:
  12. weights = [1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3]
  13. weighted_sum = sum([x * y for x, y in zip(code, weights)])
  14. check_digit = (10 - weighted_sum % 10) % 10
  15. code.append(check_digit)
  16. return ''.join(str(x) for x in code)
  17. def ean8(self):
  18. return self.ean(8)
  19. def ean13(self):
  20. return self.ean(13)