The web frame codes instance --tornado

tornado codes randomly generated image

Python random code generated by a plug-in needs to draw on, and a io module, it is also very easy, of course, need to learn from session to determine whether the error code, the following write a user login authentication with a verification code.

First, the directory structure

Two, login.html

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Title</title>
 6 </head>
 7 <body>
 8     <h1>欢迎登录</h1>
 9     <form method="POST", action="/login" enctype="multipart/form-data">
10         <p><input name="username" type="text" placeholder="用户名"></p>
11         <p><input name="pwd" type="password" placeholder="密码"></p>
12         <p>
13             <input name="code" type="text" placeholder="验证码">
14             <img src="/check_code" onclick="ChangeCode();" id=" ImgCode " >
 15          </ P>
 16          <INPUT type = " Submit " value = " Login " />
 . 17          <span style = " : Color Red " > {{State}} </ span>
 18 is      </ form>
 . 19  
20 is <Script type = " text / JavaScript " >
 21 is      function ChangeCode () {    // click on the image when the image is refreshed, it can achieve a code 
22 is          var code = document.getElementById ( ' imgCode ');
23         code.src += '?';
24     }
25 
26 </script>
27 
28 </body>
29 </html>

Three, app.py

  1 #!/usr/bin/env python
  2 # -*- coding: utf-8 -*-
  3 import tornado.ioloop
  4 import tornado.web
  5 import io
  6 import check_code
  7 
  8 container = {}
  9 class Session:
 10     def __init__(self, handler):
 11         self.handler = handler
 12         self.random_str = None
 13 
 14     def __genarate_random_str(self):
 15         import hashlib
 16         import time
. 17          obj = hashlib.md5 ()
 18 is          obj.update (bytes (STR (the time.time ()), encoding = ' UTF-. 8 ' ))
 . 19          random_str = obj.hexdigest ()
 20 is          return random_str
 21 is  
22 is      DEF __setitem __ (Self , Key, value):
 23 is          # added random string in the container
 24          # define their own special data
 25          # write random string in the client
 26          user # determination, whether there has been requested a random string
 27          iF Not self.random_str:
 28              random_str = self.handler.get_cookie ( ' __session__ ')
 29              IF Not random_str:
 30                  random_str = Self .__ genarate_random_str ()
 31 is                  Container [random_str] = {}
 32              the else :
 33 is                  # client random string
 34 is                  IF random_str in container.keys ():
 35                      Pass
 36                  the else :
 37 [                      random_str = Self .__ genarate_random_str ()
 38 is                      Container [random_str] = {}
 39              self.random_str = random_str
40  
41 is          container [self.random_str] [Key] = value
 42 is          self.handler.set_cookie ( " __session__ " , self.random_str)
 43 is  
44 is      DEF the __getitem __ (Self, Key):
 45          # acquired client random string
 46          # from container acquired their own special data
 47          # specific information [Key]
 48          random_str = self.handler.get_cookie ( " __session__ " )
 49          IF Not random_str:
 50              return None
 51 is          # client random string
 52 is          user_info_dict = Container.get(random_str, None)
 53         if not user_info_dict:
 54             return None
 55         value = user_info_dict.get(key, None)
 56         return value
 57 
 58 class BaseHandler(tornado.web.RequestHandler):
 59     def initialize(self):
 60         self.session = Session(self)
 61 
 62 
 63 class LoginHandler(BaseHandler):
 64     def get(self, *args, **kwargs):
 65         self.render('login.html', state='')
 66 
 67     def post(self, *args, **kwargs):
 68         username = self.get_argument('username', None)
 69         pwd = self.get_argument('pwd', None)
 70         code = self.get_argument('code')
 71         check_code = self.session['CheckCode']
 72         if username == 'admin' and pwd == '123' And code.upper () == check_code.upper ():
 73 is              self.write ( ' successful login ' )
 74          the else :
 75              self.render ( ' the login.html ' , State = ' user information or incorrect codes ' )
 76  
77  class CheckCodeHandler (BaseHandler):
 78      DEF GET (Self, args *, ** kwargs):
 79          Mstream = io.BytesIO ()
 80          IMG, code = check_code.create_validate_code ()
 81         img.save(mstream, "GIF")
 82         self.session['CheckCode'] = code
 83         print(mstream.getvalue())
 84         self.write(mstream.getvalue())
 85 
 86 
 87 settings = {
 88     'template_path': 'views',
 89     'static_path': 'static',
 90     'cookie_secret': 'hafhdahqahefihdkasfka',
 91 }
 92 
 93 application = tornado.web.Application([
 94     (r"/login", LoginHandler),
 95     (r"/check_code", CheckCodeHandler),
 96 ], **settings)
 97 
 98 if __name__ == "__main__":
 99     application.listen(8080)
100     tornado.ioloop.IOLoop.instance().start()

Four, check_code.py and Monaco.ttf is a plugin needs to be placed in the same directory with the app.py.

6.3.5 Operating results shown

Guess you like

Origin www.cnblogs.com/june-L/p/12070751.html