This article mainly introduces how to generate a verification code in Python, which has good practical value and clear code structure. if you need it, refer to the example below to demonstrate how to generate a verification code in Python, it has good practical value. Share it with you for your reference. The specific implementation method is as follows:
The front-end page code is as follows:
You cannot see or change one
Script function refreshCode () {$ ('authcode _ img '). src = "/registration/makeimage/" + Math. random ();} script
The background program is as follows:
Import StringIOimport Image, ImageDraw, ImageFont, and random # The corresponding module must be installed from xxx. settings import authcode_font # make sure that the modified font contains def make_image (request): mp = hashlib. md5 () mp. update (str (datetime. datetime. now () + str (random. random () mp_src = mp. hexdigest () rand_str = mp_src [0: 6] font = ImageFont. truetype (authcode_font, 25) width = 75 height = 30 im = Image. new ('rgb ', (width, height),' # % s' % mp_src [-7:-1]) draw = ImageDraw. draw (im) draw. line (random. randint (0, width), random. randint (0, height), random. randint (0, width), random. randint (0, height) draw. line (random. randint (0, width), random. randint (0, height), random. randint (0, width), random. randint (0, height) draw. line (random. randint (0, width), random. randint (0, height), random. randint (0, width), random. randint (0, height) draw. line (random. randint (0, width), random. randint (0, height), random. randint (0, width), random. randint (0, height) draw. line (random. randint (0, width), random. randint (0, height), random. randint (0, width), random. randint (0, height) draw. text (5, 2), rand_str, font = font) del draw buffer = StringIO. stringIO () im. save (buffer, 'jpeg ') httpResponse = HttpResponse (content = buffer. getvalue (), mimetype = "image/jpeg") request. session ['auth _ Code'] = rand_str return httpResponse
The program effect is as follows: