captcha.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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 ruoyi_system.service import SysConfigService
  13. from ... import reg
  14. @reg.api.route("/captchaImage")
  15. @JsonSerializer()
  16. def index_captcha_image():
  17. """
  18. 生成验证码图片
  19. :return:
  20. """
  21. captchaOnOff = SysConfigService.select_captcha_on_off()
  22. if not captchaOnOff:
  23. return AjaxResponse.from_success()
  24. ImageCaptcha.character_rotate = (-15, 15)
  25. ImageCaptcha.character_warp_dx = (0.1, 0.1)
  26. ImageCaptcha.character_warp_dy = (0.1, 0.1)
  27. ImageCaptcha.word_offset_dx = 0.1
  28. ImageCaptcha.word_space_probability = 0
  29. image = ImageCaptcha(
  30. width=160,
  31. height=60,
  32. font_sizes=[42, 45, 48]
  33. )
  34. wait_letters = string.ascii_letters + string.digits
  35. exclude_letters = "oO0iIl1"
  36. sample_letters = [i for i in wait_letters if i not in exclude_letters]
  37. code = ''.join(random.sample(sample_letters, 4))
  38. uuid_str = uuid.uuid4().hex
  39. verifyKey = Constants.CAPTCHA_CODE_KEY + uuid_str
  40. redis_cache.set(verifyKey, code, ex=Constants.CAPTCHA_EXPIRATION * 60)
  41. byte_buffer = BytesIO()
  42. try:
  43. image.write(code, byte_buffer)
  44. except Exception as e:
  45. return AjaxResponse.from_error(str(e))
  46. byte_image = byte_buffer.getvalue()
  47. ajax_response = AjaxResponse.from_success()
  48. ajax_response.uuid = uuid_str
  49. ajax_response.img = str(base64.b64encode(byte_image), encoding="utf-8")
  50. ajax_response.captchaOnOff = captchaOnOff
  51. return ajax_response