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'\xe4\xb8\xad\xe6\x96\x87'
验证码
# 需要導入模塊: 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')