captcha.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. # -*- coding: utf-8 -*-
  2. # @Author : YY
  3. import base64
  4. import random
  5. import string, uuid
  6. from captcha.image import ImageCaptcha
  7. from io import BytesIO
  8. from ruoyi_common.base.model import AjaxResponse
  9. from ruoyi_common.constant import Constants
  10. from ruoyi_common.descriptor.serializer import JsonSerializer
  11. from ruoyi_admin.ext import redis_cache
  12. from ... import reg
  13. @reg.api.route("/captchaImage")
  14. @JsonSerializer()
  15. def index_captcha_image():
  16. """
  17. 生成验证码图片
  18. :return:
  19. """
  20. ImageCaptcha.character_rotate = (-15, 15)
  21. ImageCaptcha.character_warp_dx = (0.1, 0.1)
  22. ImageCaptcha.character_warp_dy = (0.1, 0.1)
  23. ImageCaptcha.word_offset_dx = 0.1
  24. ImageCaptcha.word_space_probability = 0
  25. image = ImageCaptcha(
  26. width=160,
  27. height=60,
  28. font_sizes=[42,45,48]
  29. )
  30. wait_letters = string.ascii_letters + string.digits
  31. exclude_letters = "oO0iIl1"
  32. sample_letters = [i for i in wait_letters if i not in exclude_letters]
  33. code = ''.join(random.sample(sample_letters, 4))
  34. uuid_str = uuid.uuid4().hex
  35. verifyKey = Constants.CAPTCHA_CODE_KEY + uuid_str
  36. redis_cache.set(verifyKey, code, ex=Constants.CAPTCHA_EXPIRATION*60)
  37. byte_buffer = BytesIO()
  38. try:
  39. image.write(code, byte_buffer)
  40. except Exception as e:
  41. return AjaxResponse.from_error(str(e))
  42. byte_image = byte_buffer.getvalue()
  43. ajax_response = AjaxResponse.from_success()
  44. ajax_response.uuid = uuid_str
  45. ajax_response.img = str(base64.b64encode(byte_image),encoding="utf-8")
  46. return ajax_response