Home Backend Development Python Tutorial How to implement user identity authentication under Tornado in Python

How to implement user identity authentication under Tornado in Python

Oct 20, 2018 pm 03:21 PM
python

The content of this article is about the implementation method of user identity authentication under Tornado in Python. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

There is a current_user attribute in Tornado's RequestHandler class that is used to save the user name of the current request. The default value of RequestHandler.get_current_user is None. This attribute can be read at any time in processing functions such as get() and post() to obtain the current user name. RequestHandler.current_user is a read-only property, so if you want to set the property value, you need to overload the RequestHandler.get_current_user() function to set the property value.

Example: Use the RequestHandler.current_user attribute and the RequestHandler.get_current_user() method to implement user identity control.

Code:

import tornado.web
import tornado.ioloop
import uuid  #UUID 生成库

dict_sessions={}  #保存所有登录的Session

class BaseHandler(tornado.web.RequestHandler):  #公共基类
    #写入current_user的函数
    def get_current_user(self):
        session_id=self.get_secure_cookie("session_id")
        return dict_sessions.get(session_id)

class MainHandler(BaseHandler):
    @tornado.web.authenticated    #需要身份认证才能访问的处理器
    def get(self):
        name=tornado.escape.xhtml_escape(self.current_user)
        self.write("Hello,"+name)

class LoginHandler(BaseHandler):
    def get(self):   #登陆页面
        self.write('<html><>body'
                   '<form action="/login" method="post">'
                   'Name:<input type="text" name="name">'
                   '<input type="submit" value="Sign in">'
                   '</form></body></html>')
    def post(self):  #验证是否运行登陆
        if len(self.get_argument("name"))<3:
            self.redirect("/login")
        session_id=str(uuid.uuid1())
        dict_sessions[session_id]=self.get_argument("name")
        self.set_secure_cookie("session_id",session_id)
        self.redirect("/")
setting={
    "cookie_secret":"SECRET_DONT_LEAK", #Cookie加密秘钥
    "login_url":"/login"  #定义登陆页面
}
application=tornado.web.Application([
    (r"/",MainHandler),        #URL映射定义
    (r"/login",LoginHandler)
],**setting)

def main():
    application.listen(8888)
    tornado.ioloop.IOLoop.current().start()     #挂起监听

if __name__ == '__main__':
    main()
Copy after login

This example demonstrates a complete identity authentication programming framework. The overall idea is as follows:

  • Use the global dictionary dict_sessions to save logged in User information, for simplicity, this example only saves the key-value pair of [Reply ID: Username].

  • Define the public base class BaseHandler, which inherits from tornado.web.RequestHandler and is used to define the public properties and behaviors of all processors on this website. Overload its get_current_user() function, which is automatically called by Tornado when accessing the RequestHandler.current_user property. This function first uses get_secure_cookie() to obtain the session ID of this visit, and then uses the ID to obtain the user name from dict_sessions and returns it.

  • The MainHandler class is a handler instance that requires users to be authenticated before accessing. The processing function get() in this processor uses the decorator tornado.web.authenticated. Before execution, the processing function with this decorator determines the user's authentication status based on whether current_user has been assigned a value. If it has been assigned, it can Do the normal logic, otherwise automatically redirect to the website's login page.

  • The LoginHandler class is a login page processor, its get() function is used to render the login page, and the post() function is used to verify whether the user is allowed to log in.

  • In the initialization function of tornado.web.Application, the login page address of the website is given through the login_url parameter. This address is used by the tornado.web.authenticated decorator to redirect to a URL when it is discovered that the user has not been authenticated.

Note: All page handlers that join identity authentication need to inherit from the BaseHandler class instead of directly inheriting the original tornado.web.RequestHandler class.

Commercial identity authentication needs to improve more content, such as adding password verification mechanisms, managing login timeouts, and saving user information to the database.


The above is the detailed content of How to implement user identity authentication under Tornado in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

How to run programs in terminal vscode How to run programs in terminal vscode Apr 15, 2025 pm 06:42 PM

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

See all articles