Tornado基本使用

Tornado的安裝

1、pip3安裝
  pip3 install tornado

2、源碼安裝
        https://pypi.python.org/packages/source/t/tornado/tornado-4.3.tar.gz

Tornado基本使用

import tornado.ioloop
import tornado.web

#1、 處理訪問/index/的get請求: http://127.0.0.1:8888/index/
class MainHandler(tornado.web.RequestHandler):
   def get(self):
      self.write("I am index!!")
      # self.redirect('http://www.baidu.com')
      # self.render('index.html',k1='v1')

#2、 處理訪問 /login/的post請求和get請求: http://127.0.0.1:8888/login/
class LoginHandler(tornado.web.RequestHandler):
   def get(self):
      self.write('login')
   def post(self,*args,**kwargs):
      self.write('login post')

#3、 配置settings
settings = {
    'template_path': 'template',         # 配置html文件模板位置
    'static_path': 'static',             # 配置靜態文件路徑(圖片等)
    'static_url_prefix': '/static/',     # 前端引入靜態文件路徑
}

#4 路由系統
application = tornado.web.Application([
   (r"/index/", MainHandler),
   (r"/login/", LoginHandler),
],**settings)

#5 啓動這個tornado這個程序
if __name__ == "__main__":
   application.listen(8888)
   tornado.ioloop.IOLoop.instance().start()

Tornado各種url寫法

  • 無正則匹配url (http://127.0.0.1:8000/index/?nid=1&pid=2)
import tornado.ioloop
import tornado.web

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        nid = self.get_query_argument('nid')
        pid = self.get_query_argument('pid')
        self.write("Hello, world")

# http://127.0.0.1:8000/index/?nid=1&pid=2
application = tornado.web.Application([
    (r"/index/", MainHandler),
])

if __name__ == "__main__":
    application.listen(8000)
    tornado.ioloop.IOLoop.instance().start()
  • 基於(\d+)正則的url
import tornado.ioloop
import tornado.web

class MainHandler(tornado.web.RequestHandler):
    def get(self,nid,pid):
        print(nid,pid)
        self.write("Hello, world")

# http://127.0.0.1:8000/index/1/2/
application = tornado.web.Application([
    (r"/index/(\d+)/(\d+)/", MainHandler),        # 這種只能傳數字
    # (r"/index/(\w+)/(\w+)/", MainHandler),        # 這種可以傳數字、字母、下劃線
])

if __name__ == "__main__":
    application.listen(8000)
    tornado.ioloop.IOLoop.instance().start()
  • 基於正則分組(?P\d+),可以不考慮接收參數順序 (推薦)
import tornado.ioloop
import tornado.web

class MainHandler(tornado.web.RequestHandler):
    def get(self,nid,pid):
        print(nid,pid)
        self.write("Hello, world")

# http://127.0.0.1:8000/index/1/2/
application = tornado.web.Application([
    (r"/index/(?P<nid>\d+)/(?P<pid>\d+)/", MainHandler),        # 這種只能傳數字
])

if __name__ == "__main__":
    application.listen(8000)
    tornado.ioloop.IOLoop.instance().start()

配置settings & 獲取get,post請求

  • settings可配置參數
settings = {
    'template_path': 'template',        #配置html文件模板位置
    'static_path': 'static',             #配置靜態文件路徑(圖片等)
    'static_url_prefix': '/static/',    #前端引入靜態文件路徑
    'ui_methods': mt,
    'ui_modules': md,

    'xsrf_cookies':True,
    'cookie_secret':'xxx',
    'login_url':"/auth/login",
    'autoescape':None,
    'local':"zh_CN",
    'debug':True,
  • 獲取get、post請求

app.py

import tornado.ioloop
import tornado.web

#1、 處理訪問/index/的get請求: http://127.0.0.1:9999/index
class MainHandler(tornado.web.RequestHandler):
   def get(self):
      self.write("I am index!!")
      # self.redirect('http://www.baidu.com')
      # self.render('index.html',k1='v1')

#2、 處理訪問 /login/的post請求和get請求: http://127.0.0.1:9999/login
class LoginHandler(tornado.web.RequestHandler):
   def get(self):

      #2.1 獲取url中以get方式傳遞過來的數據: http://127.0.0.1:9999/login/?username=zhangsan
      # print(self.get_query_argument('username'))        # zhangsan
      # print(self.get_query_arguments('username'))       # ['zhangsan']
      # print( self.get_argument('username') )            # get和post兩種請求傳遞的數據都能獲取

      self.render('login.html')
   def post(self,*args,**kwargs):

      #2.2 獲取請求體中以post傳遞的數據
      # print( self.get_body_argument('faver') )     # 僅能獲取單選,多選僅能獲取最後一個
      # print( self.get_body_arguments('faver') )    # ['1', '2', '3']  獲取多選

      #2.3 get和post兩種請求傳遞的數據都能獲取
      # print( self.get_argument('username') )

      #2.4 設置和獲取cookie
      # self.cookies
      # self.set_cookie()

      #2.5 設置和獲取請求頭
      # self._headers
      # self.get_header()

      self.write('login post')

#3、 配置settings
settings = {
    'template_path': 'template',         # 配置html文件模板位置
    'static_path': 'static',             # 配置靜態文件路徑(圖片等)
    'static_url_prefix': '/static/',     # 前端引入靜態文件路徑
}

#4 路由系統
application = tornado.web.Application([
   (r"/index/", MainHandler),
   (r"/login/", LoginHandler),
],**settings)

#5 啓動這個tornado這個程序
if __name__ == "__main__":
   application.listen(9999)
   tornado.ioloop.IOLoop.instance().start()
  • /templates/login.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="/static/base.css">
</head>
<body>
    <form method="POST" action="/login/">
        <input type="text" name="username">

        <h5 class="c1">多選</h5>
            男球:<input type="checkbox" name="faver" value="1" />
            足球:<input type="checkbox" name="faver" value="2" />
            皮球:<input type="checkbox" name="faver" value="3" />
        <input type="submit" value="提交">
    </form>
</body>
</html>
  • /templates/base.css
.c1{
    color: red;
}

Tornado渲染

  • for循環

app.py

import tornado.ioloop
import tornado.web

class MainHandler(tornado.web.RequestHandler):
   def get(self):
      self.render("index.html", username='tom',list_info=[11, 22, 33],user_dic={'username':'zhangsan','age':77})

application = tornado.web.Application([
   (r"/index", MainHandler),
])

if __name__ == "__main__":
   application.listen(8888)
   tornado.ioloop.IOLoop.instance().start()

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h3>用戶名:{{username}}</h3>
    {% for item in list_info %}
        <li>{{item}}</li>
    {% end %}
    <p></p>
    {% for item in user_dic %}
        <li>{{item}} : {{user_dic[item]}}</li>
    {% end %}
</body>
</html>
  • if、in、判斷相等

app.py

import tornado.ioloop
import tornado.web

class MainHandler(tornado.web.RequestHandler):
   def get(self):
      self.render("index.html", list_info=[11, 22, 33],username='tom')

application = tornado.web.Application([
   (r"/index", MainHandler),
])

if __name__ == "__main__":
   application.listen(8888)
   tornado.ioloop.IOLoop.instance().start()

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    {% if 11 in list_info %}
        true
    {% else %}
        false
    {% end %}
    
    {% if username == "tom" %}
        my name is {{username}}
    {% else %}
        not tom
    {% end %}
</body>
</html>

Tornado多文件上傳

app.py

import tornado.ioloop
import tornado.web

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.render('index.html')

    def post(self, *args, **kwargs):
        file_metas = self.request.files["fff"]
        for meta in file_metas:
            file_name = meta['filename']
            with open(file_name,'wb') as up:
                print('hahah')
                up.write(meta['body'])

settings = {
    'template_path': 'template',
}

application = tornado.web.Application([
    (r"/index", MainHandler),
], **settings)


if __name__ == "__main__":
    application.listen(8888)
    tornado.ioloop.IOLoop.instance().start()

index.html

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <title>上傳文件</title>
</head>
<body>
    <form id="my_form" name="form" action="/index" method="POST"  enctype="multipart/form-data" >
        <input name="fff" id="my_file"  type="file" />
        <input type="submit" value="提交"  />
    </form>
</body>
</html>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章