How to implement login CAPTCHA verification with pillow in python flask
This article mainly explains "python flask how to use pillow to achieve login CAPTCHA verification", the content of the article is simple and clear, easy to learn and understand, the following please follow the editor's ideas slowly in depth, together to study and learn "python flask how to use pillow to achieve login CAPTCHA verification" bar!
1. Install pillow and write validatecode.py
From PIL import Image, ImageFont, ImageDraw, ImageFilterimport randomdef validate_picture (): total = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012345789' # picture size 130x50 width = 130 height = 50 # A new picture object im = Image.new (' RGB', (width, height), 'white') # set font font = ImageFont.truetype (' C:\ Windows\\ Fonts\\ Calibri.ttf' 50) # font = ImageFont.load_default (). Font # create draw object draw = ImageDraw.Draw (im) str1 =''# enter each text for item in range (5): text= random.choice (total) str1 + = text draw.text ((5+random.randint (4,7) + 20*item, 5+random.randint (3,7)), text=text, fill='blue' Font=font) # draw several interference lines for num in range (8): X1 = random.randint (0, width/2) y1 = random.randint (0, height/2) x2 = random.randint (0, width) y2 = random.randint (height/2, height) draw.line (x1, y1), (x2, y2)), fill='black', width=1) # blur Add a filter im = im.filter (ImageFilter.FIND_EDGES) return im, str1if _ _ name__ = ='_ _ main__': im, str1 = validate_picture () print (str1)
2. Write view function
@ admin.route ('/ login/code/') def get_code (): image, str1 = validate_picture () # CAPTCHA images are written into memory in binary form to prevent pictures from being placed in folders, occupying disk space buf = BytesIO () image.save (buf, 'jpeg') buf_str = buf.getvalue () # send binary to the front end as response And set the header field response = make_response (buf_str) response.headers ['Content-Type'] =' image/gif' # CAPTCHA string stored in seesion session ['image'] = str1 return response
3. Html template part
Administrator logs in {% for msg in get_flashed_messages ()%} {{msg}}
{% endfor%} {{form.csrf_token}} {{form.name.label}: {{form.name}} {% for err in form.name.errors%} {{err}} {% endfor%} {{form.pwd.label}: {{form.pwd}} {% for err in form .pwd.errors%} {{err}} {% endfor%} {{form.verify_code.label}: {{form.verify_code}}