第一次学习tornado小练习

内容

  这次是python的一个web框架,tornado,这个web框架在python的几个web框架中一个比较简单的web框架,刚开始接触python的时候就知道python有两个比较常用的web框架,一个是tornado,一个是Django,今天终于让我接触到tornado。

  本次的tornado的练习是一个简单的针对一个网站进行简单的后台操作,一个网站的登录验证,以及登录之后的发布信息的操作,本次练习中可能会有些地方有不足或者错误,欢迎大家来探讨或者指正我的错误,好的就不多说了,直接上代码。

  首先是一个基本的tornado的web框架,由于第一个学习,没有对这些代码进行更好的位置存放以及管理,所以请大家见谅。

  torndao.py

  1 #!/usr/bin/env python
  2 # -*- coding:utf-8 -*-
  3 
  4 
  5 import tornado.ioloop
  6 import tornado.web
  7 from nov_seven import uimethod as mt
  8 from nov_seven import uimodule as md
  9 
 10 
 11 INPUT_LIST = []
 12 USER_INFO = {'is_login':None}
 13 NEW_LIST = [
 14     {'title':'信息仿佛再次实现攻击范围来到你的面前','content':'从前你们的游戏不在是现在的我',
 15      },
 16     {'title':'信息仿佛再次实现攻击范围来到你的面前','content':'从前你们的游戏不在是现在的我',
 17      }
 18 ]
 19 #如果想在输出的时候不替换之前的内容就在新建一个字典在,它的下面,如上
 20 
 21 
 22 class MainHandler(tornado.web.RequestHandler):  
 23     #继承RequestHandler这个类                      
 24     def get(self):
 25         # self.write("Hello, world")
 26         # self.render("s1.html")  #默认到当前目录下面找
 27         # 当执行get函数的时候跳转到s1页面
 28         # self.render("s1.html", xxxooo=[11, 22, 33, 44])
 29 
 30         print(self.get_argument('name',123))
 31         print(self.get_argument('age',123))
 32         #接收通过url传输的参数
 33 
 34         #当仅仅使用url传值的时候,由于定义了xxx,但是没有传值所以出现bad request
 35         name = self.get_argument('xxx',None)    #设置默认值为None
 36         if(name):#当获取的值不为none的时候,才添加值
 37             INPUT_LIST.append(name)
 38         self.render("s1.html", xxxooo=INPUT_LIST,npm='nPm')
 39         #可以传多个值,传值之后就可以在html文件里使用这个参数
 40 
 41     def post(self, *args, **kwargs):
 42         # self.write("Hello")
 43         # print('post')
 44 
 45         name = self.get_argument('xxx')    
 46         #name拿到的是表单里提交的数据
 47         INPUT_LIST.append(name)
 48         self.render("s1.html", xxxooo=INPUT_LIST)
 49         print(INPUT_LIST)
 50 
 51 #render内部应该是打开文件将文件的内容返回
 52 #1.打开s1.html文件,读取内容(包含特殊语法)
 53 #2.当这里的render里添加第二参数的时候,xxxooo = [11,22,33,44]&&读取内容(包含特殊语法)
 54 # 这里为2的示例  (self.render("s1.html",xxxooo=[11,22,33,44]))
 55 #3.得到新的字符串(就是已经替换完毕的字符串)
 56 #4.返回给用户
 57 
 58 
 59 class IndexHandler(tornado.web.RequestHandler):
 60     def get(self,*args,**kwargs):
 61         self.render('index.html',is_login = USER_INFO,new_list = NEW_LIST)
 62 
 63 
 64 class LoginHandler(tornado.web.RequestHandler):
 65     def post(self,*args,**kwargs):
 66         username = self.get_argument('username',None)
 67         passwd = self.get_argument('passwd',None)
 68         if username == 'alexsel'and passwd == '123456':
 69             USER_INFO['is_login'] = True
 70             USER_INFO['username'] = username
 71         # self.render('index.html',is_login = USER_INFO['is_login'],is_name = USER_INFO['username'])
 72         # self.render('index.html', is_login=USER_INFO,new_list = NEW_LIST)
 73         #传字典方式失败,以后进行修改,三 115 24,自己发现错误成功使用字典方式传递错误
 74 
 75         self.redirect('index')
 76         # 跳转到的url
 77 
 78 class PublishHandler(tornado.web.RequestHandler):
 79     def post(self,*args,**kwargs):
 80         if USER_INFO['is_login']:
 81             headline = self.get_argument('headline', None)
 82             words = self.get_argument('words', None)
 83             temp = {'title':headline, 'content':words}
 84             NEW_LIST.append(temp)
 85         # self.render('index.html',insertcontnet=temp)
 86         self.redirect('index')
 87         #跳转到index页面,同时NEW_LIST已经更新,所以自己添加的内容就刷新到了页面上
 88 
 89 settings = {
 90     "template_path":"template", #模版路径的配置        
 91     "static_path":"static",
 92     "static_url_prefix":"/sss/",
 93     "ui_methods":mt,
 94     "ui_modules":md,
 95 }
 96 # template_path
 97 #配置参数,用来添加寻找目录template_path为固定写法,:后面为目录,就像上面的s1在template下面,然而没有写
 98 #路径仅仅是写了文件名就可以执行,因为添加查询目录在里面
 99 
100 #static_path
101 #静态文件的配置(写程序的时候会把CSS,javascript都当作静态文件来处理,所以这些文件必须放在特殊的文件夹里)
102 #就像你引入的CSS文件(自己定义样式),无论你怎莫修改样式都无法找到这个CSS文件,所以需要特殊处理
103 
104 #static_url_prefix
105 # 静态文件的前缀,就像s1里href的static一样,定义之后添加这个前缀,写上这个前缀就代表去static_path定义的目录
106 #里(static)面找,自己看s1文件里的写法
107 
108 #ui_methods
109 #自己定义的函数(方法),通过import把含有自己定义方法的py文件引入进来,引入到进来,这个mt是别名,在这里声明(注册)
110 #之后就可以在与这个相关联的html文件里使用这个文件里的定义的方法了
111 
112 #ui_modules
113 #将有自己定义的类的文件引入进来,然后再这里声明(注册),然后就可以在关联的html文件里使用这个类
114 
115 
116 #静态文件还可以做进一步的处理
117 
118 
119 
120 #路由映射,路由系统
121 application = tornado.web.Application([
122     # (r"/index", MainHandler),
123     (r"/index",IndexHandler),
124     (r"/login", LoginHandler),
125     (r'/publish',PublishHandler)
126 ],**settings)
127 
128 #创建了一个对象
129 #检索你输入的url是否和上面的index是否匹配,匹配之后自动执行后面那个类,然后自动执行后面的那个
130 #get方法,这个执行这个get方法就是一个定死的,是一个规定,好像必须是get这个才行
131 #第二个这个Application的第二个参数为配置参数,
132 #这个使用get还是post方法是要看html里的form表单里method的值是什么,这里就选择什么方式(post/get)
133 
134 
135 
136 
137 if __name__ == "__main__":
138     application.listen(8888)
139     tornado.ioloop.IOLoop.instance().start()
140     # 里面执行了socket

接下来就是页面的代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="{{static_url('plugins/bootstrap3/css/bootstrap.css')}}">
    <style>
        img{
            border:0;
        }
        ul{
            list-style: none;
            margin-top:0;
        }
        li {
            float: left;
        }

        body{
            margin:0;
            background-color: gainsboro;
        }
        div .sm  li a{

            font-family:方正姚体;
            padding:0 10px ;
            color: white;
            font-size: 15px;
            /* 40px;*/
            text-decoration: none;
        }
        .one .wtp .menu li:hover{
            background-color: red;

        }
        .one .menu .login li:hover{
            background-color: red;
        }
        body{
            border-right: 1px;
            margin: 0;
        }
        .one{
            background-color:#2459a2;


        }
         .wtp{
             background-color:#2459a2;
             width: 980px;
             height: 28px;
             margin: 0 auto;

        }
        .imgan{
            margin-top: 5px;
            float: left;
        }
        .one .menu{
            float: left;
            line-height: 28px;

        }
        .one .wtp .search{
            float: right;
            margin-top: 2px;
        }
        .one .wtp .login ul{
            margin-top: 2px;
            float: right;
            list-style-type:none;
            margin-left: 100px;
        }
        .one .login a{
            font-size: 15px;
            font-family:方正姚体;
           text-decoration: none;
            color: white;
        }
        .two{
            margin: 0;
            padding:0;
            /*background-color: white;*/
        }
        .two .b_body{
            background-color: white;
            padding: 0;
            width: 850px;
            margin:0 auto;
        }
        .two .b_body .body_right{
            float: right;
            width: 250px;
            background-color: white;
            /*margin-left: px;*/
        }
        .two .b_body .body_left{
            border: 0;
            float: left;
            width: 600px;
            height: 1000px;
            background-color: white;
        }
        .two .body_left .tp1 li{
            margin-top: 15px;
            padding: 0 10px;
            font-size: 15px;
            font-family: 楷体;
            text-decoration: none;
        }
        .two .body_left .tp2 li{
            padding:0 10px;
            font-size: 14px;
            float: right;
            text-decoration: none;
        }
        .two .body_left .tyj p{
            width: 450px;
            font-family: 楷体;
            padding:0 20px;
            font-size: 14px;


        }
        .two .body_left .tyj p a{
            color: #369;
            text-decoration: none;
        }
        .two .body_left .tyj p a:hover{
            color: purple;
        }
        .two .tyj img{
            float: right;
            margin:0 10px;
            width: 60px;
            height: 60px;
        }
        .footer{
            background-color: #2459a2;
            clear: both;
        }
        .body_right p{
            width: 195px;
            margin:0 auto;
        }
        .body_right a{
            color: darkgray;
            padding:0 20px;
            font-size: 12px;
            font-family: 微软雅黑;


        }
        .body_right a:hover{
            color: purple;
        }


    </style>
</head>
<body>
    <div style="float: left ;position: fixed;"  class="sivier">
        <img  style="100px;height:100px" src="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1506189359107&di=2920620b7071efc5f9e5e5835198e10e&imgtype=0&src=http%3A%2F%2Fwww.people.com.cn%2Fmediafile%2Fpic%2F20150619%2F42%2F17794731963561654358.jpg">
    </div>
    <div class="one">
        <div class="wtp">
            <div class="imgan">
                <img style="85px;" src="http://dig.chouti.com/images/logo.png"/>
            </div>
            <div class="menu">
                <ul class="sm">
                    <li><a href="http://baidu.com">全部</a></li>
                    <li><a href="http://baidu.com">42区</a></li>
                    <li><a href="http://baidu.com">段子</a></li>
                    <li><a href="http://baidu.com">图片</a></li>
                    <li><a href="http://baidu.com">挨踢1024</a></li>
                    <li><a href="http://baidu.com">你问我答</a></li>
                </ul>
            </div>
            <div class="search">
                <form action="https://baidu.com/s?">
                <input type="text" name="wd" value="百度一下你就知道" />
                </form>
            </div>
            <div class="login">
                <ul>
                    {% if is_login['is_login'] %}
                    <li><a href="index.html">{{is_login['username']}}</a></li>
                    {% else %}
                    <li><a id="undid" href="#" onclick="Login();">登录</a></li>
                    <li><a>注册</a></li>
                    {%end%}
                </ul>
            </div>
        </div>
    </div>
    <div   class="two">
        <div  class="b_body">
            <div class="body_left">
                <ul class="tp1">
                    <li><a href="http://baidu.com">最热</a></li>
                    <li><a href="http://baidu.com">发现</a></li>
                    <li><a href="http://baidu.com">人类发布</a></li>
                </ul>
                <ul class="tp2">
                    <li><a href="#" onclick="Insert();">+发布</a></li>
                    <li><a href="http://baidu.com">24小时3天</a></li>
                    <li><a href="http://baidu.com">即时排序</a></li>
                </ul>
                <br>
                <div class="tyj">
                    {% for new in new_list %}
                    <hr>
                    <div class="item">
                        <img src="/index.html/img3.chouti.com/CHOUTI_0EFA5D07942D4E6B818D8E26FA4D6AAB_W320H320=C60x60.jpg">
                    <p>
                        <a style="font-size:20px;color:darkblue;" href="http://baidu.com">
                            {{new['title']}}
                        </a>
                        <p><a>{{new['content']}}</a></p>

                    </p>
                    <a style="font-size: 10px" src="sss">
                        <img style=" 10px;height: 10px;float: left;" src="https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=244214795,2938463942&fm=27&gp=0.jpg">
                        520
                    </a>
                    </div>
                    {%end%}


                    <!--<hr>-->
                    <!--<div class="item">-->
                        <!--<img src="/index.html/img3.chouti.com/CHOUTI_0EFA5D07942D4E6B818D8E26FA4D6AAB_W320H320=C60x60.jpg">-->
                    <!--<p>-->
                        <!--<a href="http://baidu.com">-->
                            <!--抽屉新热榜今天中午12点起开始实行实名制,未绑定过手机号的老用户注意了!-->
                        <!--</a>-->
                    <!--</p>-->
                    <!--<a style="font-size: 10px" src="sss">-->
                        <!--<img style=" 10px;height: 10px;float: left;" src="https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=244214795,2938463942&fm=27&gp=0.jpg">-->
                        <!--520-->
                    <!--</a>-->
                    <!--</div>-->
                    <!--<hr>-->
                    <!--<div class="item">-->
                        <!--<img src="http://img5.imgtn.bdimg.com/it/u=1116060335,1837790544&fm=27&gp=0.jpg">-->
                    <!--<p>-->
                        <!--<a href="http://baidu.com">【传奇步枪AK-47诞生70年 俄罗斯立世界枪王铜像】今年是传奇步枪AK-47诞生70周年, 9月19日,俄罗斯为其发明者卡拉-->
                            <!--什尼科夫举行了纪念仪式,并在莫斯科为他树立起一座雕像。据统计,卡拉什尼科夫研发的枪械产量已超过一亿支,装备了100多个国家的武装力量。他也被称为世界枪王。-->
                        <!--</a>-->
                    <!--</p>-->

                    <!--</div>-->

                    <!--<hr>-->
                    <!--<div class="item">-->
                        <!--<img src="http://img3.chouti.com/CHOUTI_AF567EAA9C84489691D5F196D5AAB07E_W285H285=C200x200.jpg">-->
                    <!--<p>-->
                        <!--<a href="http://baidu.com">【关于今天下午朝鲜地震的各方表态】中国地震局:疑爆;韩国气象厅:自然地震;-->
                            <!--日本政府相关人士:目前正在收集信息,但现阶段没有官邸干部的紧急集合;俄罗斯气象部门官员:辐射量与往常数值无异,-->
                            <!--未观测到异常情况。朝鲜过去实施的核试验均观测到了里氏4.0级以上的地震。-->
                        <!--</a>-->
                    <!--</p>-->


                    <!--</div>-->

                    <!--<hr>-->
                    <!--<div class="item">-->
                        <!--<img src="http://img3.chouti.com/CHOUTI_4052A9DC4A16491D934190069C273380_W1280H960=C60x60.jpg">-->
                    <!--<p>-->
                        <!--<a href="http://baidu.com">有钱人的精致生活-->
                            <!--<br>-->
                            <!--<br>-->
                            <!--<br>-->
                        <!--</a>-->
                    <!--</p>-->
                    <!--</div>-->

                    <!--<hr>-->
                    <!--<div class="item">-->
                        <!--<img src="http://img3.chouti.com/CHOUTI_AAB2CE03F61041AF811420E8DC2DCF34_W550H412=C60x60.jpg">-->
                    <!--<p>-->
                        <!--<a href="http://baidu.com">【数据显示:有了共享单车,广州拥堵下降6.8%】交通部科学研究院的报告显示,在共享单车推出之后,-->
                            <!--广州和深圳的拥堵程度分别下降6.8%和4.1%,同时自行车出行的占比从5.5%翻倍增长到了11.6%。-->
                        <!--</a>-->
                    <!--</p>-->
                    <!--</div>-->

                </div>
            </div>
            <div class="body_right">
                <img style="margin: 10px 10px 10px 25px;  200px; height: 150px" src="http://dig.chouti.com//images/homepage_download.png">
                <HR style="border:1 dashed #987cb9" width="80%" color=#987cb9 SIZE=1>
                <p>
                    <a href="http://img1.qq.com/ent/pics/17553/17553008.jpg">
                        3.1415926545
                    </a>
                </p>
                <HR style="border:1 dashed #987cb9" width="80%" color=#987cb9 SIZE=1>
                <p>
                    <a href="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1506782933&di=dec08e284975eb316d19dd9ae83e51c2&imgtype=jpg&er=1&src=http%3A%2F%2Fi1.sinaimg.cn%2Ftravel%2F2010%2F0817%2F201081795558.jpg">
                        3.1415926545
                    </a>
                </p>
            </div>
            <div style="clear: both;"></div>
        </div>
    </div>

    <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel">
      <div class="modal-dialog" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            <h4 class="modal-title" id="exampleModalLabel">用户登录</h4>
          </div>
            <form action="/login" method="post">
                <div class="modal-body">

              <div class="form-group">
                <label  class="control-label">用户名:</label>
                <input type="text" name="username" class="form-control">
              </div>
              <div class="form-group">
                <label class="control-label">密码:</label>
                <!--<textarea class="form-control" id="message-text"></textarea>-->
                  <input type="password" name="passwd" class="form-control">
              </div>

          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            <button type="submit" class="btn btn-primary">登录</button>
          </div>
            </form>
        </div>
      </div>
    </div>
    <div class="modal fade" id="exampleModal_pub" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel">
      <div class="modal-dialog" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            <h4 class="modal-title" id="exampleModalLabel_pub">发布内容</h4>
          </div>
            <form method="post" action="/publish">
              <div class="modal-body">

                  <div class="form-group">
                    <label for="recipient-name" class="control-label">标题:</label>
                    <input type="text" name="headline" class="form-control" id="recipient-name">
                  </div>
                  <div class="form-group">
                    <label for="message-text" class="control-label">内容:</label>
                    <textarea class="form-control" name="words" id="message-text"></textarea>
                  </div>

              </div>
              <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <button type="submit" class="btn btn-primary">发布内容</button>
              </div>
         </form>
        </div>
      </div>
    </div>
    <div class="footer">r</div>
<script src="{{static_url('jquery-1.10.2.js')}}"></script>
    <script src="{{static_url('plugins/bootstrap3/js/bootstrap.js')}}"></script>
<script>
        function Login(){
            $('#exampleModal').modal('show');

        }
        function Insert(){
            $('#exampleModal_pub').modal('show');
        }
</script>
</body>
</html>

这个练习就是有关于前端后端简单的数据交互,第一次学习tornado,以后还要多加练习。

  

原文地址:https://www.cnblogs.com/liudi2017/p/7880731.html