• captcha


    String模块ascii_letters和digits

    >>> chars = string . ascii_letters + string . digits
    >>> print ( chars )
    abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789

     

    captcha

     

    io.BytesIO()

    BytesIO

    StringIO操作的只能是str,如果要操作二进制数据,就需要使用BytesIO。

    BytesIO实现了在内存中读写bytes,我们创建一个BytesIO,然后写入一些bytes:

    >>> from io import BytesIO
    >>> f = BytesIO()
    >>> f.write('中文'.encode('utf-8'))
    6
    >>> print(f.getvalue())
    b'xe4xb8xadxe6x96x87'

    验证码

    # 需要導入模塊: from captcha import image [as 別名]
    # 或者: from captcha.image import ImageCaptcha [as 別名]
    def create_image_captcha(captcha_text):
        image_captcha = ImageCaptcha()
        # Create the captcha image.
        image = image_captcha.generate_image(captcha_text)
    
        # Add noise curve for the image.
        # image_captcha.create_noise_curve(image, image.getcolors())
    
        # Add noise dots for the image.
        # image_captcha.create_noise_dots(image, image.getcolors())
    
        # Save the image to a png file.
        image_file = "./captcha_"+captcha_text + ".png"
        imgByteArr = BytesIO()
        image.save(imgByteArr, format='PNG')
        imgByteArr = imgByteArr.getvalue()
        open("test.png", "wb").write(imgByteArr)
        #image_captcha.write(captcha_text, image_file)
    
        print(image_file + " has been created.")
    
    # Create an audio captcha file. 
    import io
    import random
    import string
    
    from captcha.image import ImageCaptcha
    from fastapi import APIRouter, Path
    from fastapi.responses import Response
    
    import crud
    router = APIRouter()
    
    chars = string.ascii_letters + string.digits
    
    
    @router.get('/{uuid}', response_class=Response, description="获取验证码,用于用户登陆与注册页面")
    async def get_captcha(
            uuid: str = Path(..., description="由前端生成的验证码的uuid,页面每次刷新是应当更新该uuid,只更新验证码时可以复用")
    ):
        captcha_text = ''.join(random.sample(chars, 4))
        captcha_image = ImageCaptcha().generate_image(captcha_text)
        captcha_image_bytes_io = io.BytesIO()
        captcha_image.save(captcha_image_bytes_io, format='png')
    
        await crud.captcha.save_captcha(uuid, captcha_text)
        return Response(captcha_image_bytes_io.getvalue(), media_type='image/png')
  • 相关阅读:
    Java进阶知识查漏补缺05
    Java进阶知识查漏补缺04
    Java进阶知识查漏补缺03
    Java进阶知识查漏补缺02
    Java进阶知识查漏补缺01
    在IDEA下导入项目后,WEB网页只显示jsp源码的解决方法
    Tutorial 3_工厂方法模式
    Tutorial 2_简单工厂模式
    Tutorial 1_UML与面向对象程序设计基本原则
    Java知识查漏补缺-04
  • 原文地址:https://www.cnblogs.com/Mint-diary/p/14442039.html
Copyright © 2020-2023  润新知