• 18.Tornado_个人信息案例


    1.Tornado_个人信息案例_环境搭建

    1.1概述

    由于这次是前后端不分离的小型项目案例,就不编写前端代码,前端代码直接展示出来,对应粘贴到template、static的文件夹中即可。

    1.2流程概述

    1. 导入前端资源,我已经上传资源到文件夹中咯
    2. 修改person18.html的herf路径,用static_url
    3. VSCode下载Mysql插件
      在这里插入图片描述
    4. 连接数据库,创建数据库tornado_db
    5. 创建表——t_user
      在这里插入图片描述

    1.3 环境搭建代码展示

    1.3.1 sql创建表

    -- Active: 1664001218471@@127.0.0.1@3306@tornado_db
    CREATE TABLE t_user(  
        id int PRIMARY KEY AUTO_INCREMENT,
        uname VARCHAR(32),
        nick_name VARCHAR(32),
        email VARCHAR(32),
        pwd VARCHAR(32),
        phone VARCHAR(32),
        language VARCHAR(64)
    ) COMMENT '';
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    1.3.2 Tornado

    from tornado.web import Application, RequestHandler
    from tornado.ioloop import IOLoop
    
    class IndexHandle(RequestHandler):
        async def get(self):
            self.render('personal18.html')
    
    
    if __name__ == '__main__':
        import os
        # 获取绝对路径
        base_path = os.path.abspath(os.path.dirname(__file__))
        # 设置应用参数
        settings = {
            'template_path':os.path.join(base_path, 'templates'),
            'static_path': os.path.join(base_path, 'static'),
            'static_url_prefix': '/static/',
            'debug': True
        }
        # 创建Tornado应用
        app = Application([('/',IndexHandle)], **settings)
        # 设置监听端口号
        app.listen(8000)
        IOLoop.current().start()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24

    2.Tornado_整合aiomysql模块

    2.1异步操作Mysql方法:

    参考链接:如何异步操作mysql

    2.2 获取数据库信息——参考2.1,并完成数据回显

    将2.1的方法粘贴到get(self)中,并把查询出的结果当成参数传递给;
    在html的form表单中绑定数据,让其显示到form表单中

     <input class="au-input au-input--full" type="text" name="username" placeholder="Username" value="{{user[1]}}">
    
    • 1

    2.3 提取数据库中的参数——展示2.的完整代码

    from tornado.web import Application, RequestHandler, URLSpec
    from tornado.ioloop import IOLoop
    import asyncio
    import aiomysql
    
    class IndexHandle(RequestHandler):
        # 首先由Application创建路由地址时,携带参数传递会到initialize,去定义一个self.mysql用于get中获取参数
        def initialize(self,mysql):
            self.mysql = mysql
        async def get(self):
            print(self.mysql)
            # 获取1个客户端链接池
            async with aiomysql.create_pool(
                host=self.mysql.get('host'),
                port=self.mysql.get('port'),
                user=self.mysql.get('user'),
                password=self.mysql.get('pwd'),
                db=self.mysql.get('db')) as pool:
                # 获取1个链接,用来获取游标
                async with pool.acquire() as con:
                    # 获取一个游标,用来操作数据库
                    async with con.cursor() as cur:
                        # 执行sql
                        # sql = 'select 101'
                        sql = 'select * from t_user'
                        await cur.execute(sql)
                        # 获取结果
                        rs = await cur.fetchone()
                        print(rs)
            self.render('personal20.html',user = rs)
    
    
    if __name__ == '__main__':
        import os
        # 获取绝对路径
        base_path = os.path.abspath(os.path.dirname(__file__))
        # 设置应用参数
        settings = {
            'template_path':os.path.join(base_path, 'templates'),
            'static_path': os.path.join(base_path, 'static'),
            'static_url_prefix': '/static/',
            'debug': True,
            # 为了方便数据库的修改,可以直接把参数单独放在这
            'mysql': {
                'host': '127.0.0.1',
                'port': 3306,
                'user': 'root',
                'pwd': 'root',
                'db': 'tornado_db'
            }
        }
        # 创建Tornado应用
        app = Application([
            URLSpec('/',IndexHandle, {'mysql':settings.get('mysql')})
            ], **settings)
        # 设置监听端口号
        app.listen(8000)
        IOLoop.current().start()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58

    html:

    DOCTYPE html>
    <html lang="cn">
    <head>
        <meta charset="UTF-8">
        
        <title>个人信息title>
        
        <link href="{{static_url('css/bootstrap.min.css')}}" rel="stylesheet" media="all">
        
        <link href="{{static_url('css/theme.css')}}" rel="stylesheet" media="all">
    head>
    
    <body class="animsition">
        <div class="page-wrapper">
            <div class="page-content--bge5">
                <div class="container">
                    <div class="login-wrap">
                        <div class="login-content">
                            <div class="login-logo">
                                <a href="#">
                                    <img src="{{static_url('img/logo2.png')}}" alt="CoolAdmin">
                                a>
                            div>
                            <div class="login-form">
                                <form action="/" method="post">
                                    <div class="form-group">
                                        <label>用户名label>
                                        <input class="au-input au-input--full" type="text" name="username" placeholder="Username" value="{{user[1]}}">
                                    div>
                                    <div class="form-group">
                                        <label>昵称label>
                                        <input class="au-input au-input--full" type="text" name="nick_name" placeholder="NickName" value="{{user[2]}}">
                                    div>
                                    <div class="form-group">
                                        <label>邮箱label>
                                        <input class="au-input au-input--full" type="email" name="email" placeholder="Email" value="{{user[3]}}">
                                    div>
                                    <div class="form-group">
                                        <label>密码label>
                                        <input class="au-input au-input--full" type="password" name="password" placeholder="Password" value="{{user[4]}}">
                                    div>
                                    <div class="form-group">
                                        <label>联系电话label>
                                        <input class="au-input au-input--full" type="text" name="phone" placeholder="Phone" value="{{user[5]}}">
                                    div>
                                    <div class="form-group">
                                        <label>擅长语言label>
                                        <input class="au-input au-input--full" type="text" name="language" placeholder="Language" value="{{user[6]}}">
                                    div>
                                    <button class="au-btn au-btn--block au-btn--green m-b-20" type="submit">确 认button>
                                form>
                            div>
                        div>
                    div>
                div>
            div>
        div>
    body>
    html>
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60

    3.Tornado_增加数据

    3.1流程概述

    1. 获取请求体参数并存放到args中获取参数方法
    2. 链接数据库
    3. 提交sql
    4. 提交事务
    5. 先添加id字段(否则字段长度不够,前端获取会报错),返回模板内容

    3.2代码展示

        async def post(self):
            # 获取前端传递来的数据
            name = self.get_argument('username')
            nick_name = self.get_body_argument('nick_name')
            email = self.get_argument('email')
            password = self.get_body_argument('password')
            phone = self.get_argument('phone')
            language = self.get_body_argument('language')
    
            args = [name,nick_name,email,password,phone,language]
            # 链接数据库
            # 获取1个客户端链接池
            async with aiomysql.create_pool(
                host=self.mysql.get('host'),
                port=self.mysql.get('port'),
                user=self.mysql.get('user'),
                password=self.mysql.get('pwd'),
                db=self.mysql.get('db')) as pool:
                # 获取1个链接,用来获取游标
                async with pool.acquire() as con:
                    # 获取一个游标,用来操作数据库
                    async with con.cursor() as cur:
                        sql = 'insert into t_user values(0, %s, %s, %s, %s, %s, %s)'
                        await cur.execute(sql, args) 
                        # 提交事务
                        await cur.commit()
                        # 获取生成的id
                        id = con.lastrowid
                        # 存放id到args中
                        args.insert(0,id)
            self.render('personal21.html', user = args)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31

    4.Tornado_修改数据

    4.1概述

    由于只是案例展示,就不单独开一个路由去做这个业务了。基本的思路就是,先在前端中利用第一步的get请求,去尝试获取用户的id(但不显示),然后返回给后端。后端做一个判断,是否有id这个值存在,如果有,就进行修改,没有就增加数据。

    4.2代码展示

    from tornado.web import Application, RequestHandler, URLSpec
    from tornado.ioloop import IOLoop
    import asyncio
    import aiomysql
    
    class IndexHandle(RequestHandler):
        # 首先由Application创建路由地址时,携带参数传递会到initialize,去定义一个self.mysql用于get中获取参数
        def initialize(self,mysql):
            self.mysql = mysql
    
        async def get(self):
            print(self.mysql)
            # 获取1个客户端链接池
            async with aiomysql.create_pool(
                host=self.mysql.get('host'),
                port=self.mysql.get('port'),
                user=self.mysql.get('user'),
                password=self.mysql.get('pwd'),
                db=self.mysql.get('db')) as pool:
                # 获取1个链接,用来获取游标
                async with pool.acquire() as con:
                    # 获取一个游标,用来操作数据库
                    async with con.cursor() as cur:
                        # 执行sql
                        # sql = 'select 101'
                        sql = 'select * from t_user'
                        await cur.execute(sql)
                        # 获取结果
                        rs = await cur.fetchone()
                        print(rs)
            self.render('personal22.html',user = rs)
        
        
        
    
        async def post(self):
            # 获取前端传递来的数据
            uname = self.get_argument('username')
            nick_name = self.get_body_argument('nick_name')
            email = self.get_argument('email')
            password = self.get_body_argument('password')
            phone = self.get_argument('phone')
            language = self.get_body_argument('language')
            try:
                # 获取id
                id = self.get_body_argument('id')
            except Exception as e:
                id = False
    
            args = [uname,nick_name,email,password,phone,language]
            # 链接数据库
            # 获取1个客户端链接池
            async with aiomysql.create_pool(
                host=self.mysql.get('host'),
                port=self.mysql.get('port'),
                user=self.mysql.get('user'),
                password=self.mysql.get('pwd'),
                db=self.mysql.get('db')) as pool:
                # 获取1个链接,用来获取游标
                async with pool.acquire() as con:
                    # 获取一个游标,用来操作数据库
                    async with con.cursor() as cur:
                        if not id:
                            sql = 'insert into t_user values(0, %s, %s, %s, %s, %s, %s)'
                            await cur.execute(sql, args) 
                            # 提交事务
                            await con.commit()
                            # 获取生成的id
                            id = cur.lastrowid
                        else:
                            sql = 'update t_user set uname=%s, nick_name=%s, email=%s, pwd=%s, phone=%s, language=%s where id=%s'
                            # 增加id来告诉数据库更新哪一条数据
                            args.append(id)
                            await cur.execute(sql, args)
                            await con.commit()
                        # 存放id到args中
                        args.insert(0,id)
            self.render('personal22.html', user = args)
    
    
    
    if __name__ == '__main__':
        import os
        # 获取绝对路径
        base_path = os.path.abspath(os.path.dirname(__file__))
        # 设置应用参数
        settings = {
            'template_path':os.path.join(base_path, 'templates'),
            'static_path': os.path.join(base_path, 'static'),
            'static_url_prefix': '/static/',
            'debug': True,
            # 为了方便数据库的修改,可以直接把参数单独放在这
            'mysql': {
                'host': '127.0.0.1',
                'port': 3306,
                'user': 'root',
                'pwd': 'root',
                'db': 'tornado_db'
            }
        }
        # 创建Tornado应用
        app = Application([
            URLSpec('/',IndexHandle, {'mysql':settings.get('mysql')})
            ], **settings)
        # 设置监听端口号
        app.listen(8000)
        IOLoop.current().start()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107

    4.3当没有数据时,前端无法获取的报错问题

    只需要在前端的获取数据的value中判断是否存在user即可

    4.4代码展示

    DOCTYPE html>
    <html lang="cn">
    <head>
        <meta charset="UTF-8">
        
        <title>个人信息title>
        
        <link href="{{static_url('css/bootstrap.min.css')}}" rel="stylesheet" media="all">
        
        <link href="{{static_url('css/theme.css')}}" rel="stylesheet" media="all">
    head>
    
    <body class="animsition">
        <div class="page-wrapper">
            <div class="page-content--bge5">
                <div class="container">
                    <div class="login-wrap">
                        <div class="login-content">
                            <div class="login-logo">
                                <a href="#">
                                    <img src="{{static_url('img/logo2.png')}}" alt="CoolAdmin">
                                a>
                            div>
                            <div class="login-form">
                                <form action="/" method="post">
                                    <div class="form-group">
                                        {% if user %}
                                            <input type="hidden" name="id" value={{user[0]}}>
                                        {% end %}
                                        <label>用户名label>
                                        <input class="au-input au-input--full" type="text" name="username" placeholder="Username" {% if user %} value={{user[1]}} {% end %}>
                                    div>
                                    <div class="form-group">
                                        <label>昵称label>
                                        <input class="au-input au-input--full" type="text" name="nick_name" placeholder="NickName" {% if user %} value="{{user[2]}}" {% end %}>
                                    div>
                                    <div class="form-group">
                                        <label>邮箱label>
                                        <input class="au-input au-input--full" type="email" name="email" placeholder="Email" {% if user %} value="{{user[3]}}" {% end %}>
                                    div>
                                    <div class="form-group">
                                        <label>密码label>
                                        <input class="au-input au-input--full" type="password" name="password" placeholder="Password" {% if user %} value="{{user[4]}}" {% end %}>
                                    div>
                                    <div class="form-group">
                                        <label>联系电话label>
                                        <input class="au-input au-input--full" type="text" name="phone" placeholder="Phone" {% if user %} value="{{user[5]}}" {% end %}>
                                    div>
                                    <div class="form-group">
                                        <label>擅长语言label>
                                        <input class="au-input au-input--full" type="text" name="language" placeholder="Language" {% if user %} value="{{user[6]}}" {% end %}>
                                    div>
                                    <button class="au-btn au-btn--block au-btn--green m-b-20" type="submit">确 认button>
                                form>
                            div>
                        div>
                    div>
                div>
            div>
        div>
    body>
    html>
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
  • 相关阅读:
    Linux:Gitlab:16.9.2 创建用户及项目仓库基础操作(2)
    【ChatGPT系列】ChatGPT:创新工具还是失业威胁?
    Pytorch实用教程:pytorch中可以做哪些优化,以提高模型的识别精度
    前端性能精进之浏览器(五)——JavaScript
    磁珠元器件:微小却强大的科技奇迹 | 百能云芯
    优维低代码实践:打包发布
    负载均衡与高可用
    并查集略解
    鱼哥赠书活动第③期:《CTF那些事儿》《构建新型网络形态下的网络空间安全体系》《智能汽车网络安全权威指南》上下册
    python批量重命名工具
  • 原文地址:https://blog.csdn.net/m0_63953077/article/details/127719876