1. 程式人生 > >tornado學習日記(1)

tornado學習日記(1)

第一個簡單應用

import tornado.ioloop
import tornado.web
import tornado.httpserver
import tornado.options
from tornado.options import define, options

#定義埠配置
define('port', type=int, default=8080)

#建立檢視處理器
class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.write("<h1>hello,world</h1>")

#建立路由表
urls = [(r"/", MainHandler),]

#建立配置-開啟除錯模式
configs = dict(debug=True)
#自定義應用
class MyApplication(tornado.web.Application):
    def __init__(self, urls, configs):
        super(MyApplication, self).__init__(handlers=urls, **configs)
#建立伺服器
def make_app():
    tornado.options.parse_command_line()
    http_server = tornado.httpserver.HTTPServer(MyApplication(urls,configs))
    http_server.listen(options.port)
    tornado.ioloop.IOLoop.current().start()

#啟動伺服器
if __name__ == '__main__':
    make_app()

三、路由

1.多個路由志同一個地址

#建立檢視處理器
class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.write("<h1>享學課堂-Tornado教程</h1>")

#建立路由表
urls = [
    (r"/", MainHandler),
    (r"/index",MainHandler)
]

2.帶數字引數的路由

class CourseHandler(tornado.web.RequestHandler):
    def get(self,cid ):
        self.write('<h1>享學課堂-當前課程ID:%d</h1>'%(int(cid)))

#建立路由表
urls = [
    (r"/", MainHandler),
    (r"/index",MainHandler),
    (r'/course/(d+)',CourseHandler),
    (r'/course/([0-9]+)',CourseHandler),
]

3.帶字串引數路由

class CourseHandler2(tornado.web.RequestHandler):
    def get(self,name ):
        self.write('<h1>享學課堂-當前課程名稱:%s</h1>'%(name))

#建立路由表
urls = [

    (r'/course2/([a-zA-Z]+)',CourseHandler2)
]

4.帶中文引數路由

    (r'/cdetail/(.*)',CourseDetailHandler)

5.多個引數路由:

class CourseDetailHandler3(tornado.web.RequestHandler):
    def get(self, cid, name):
        self.write('課程ID:%d<br>課程名稱:%s' % (int(cid), name))
urls = [
    (r'/course3/(\d+)/(.*)',CourseDetailHandler3)
]

6.帶引數名稱的路由

 

7.路由生成器

匯入

from tornado.web import url, URLSpec

設定路由名稱

urls = [
    url(r"/course/(\d+)", CourseHandler,name='course'),
]

使用reverse_url獲得路由

class CourseHandler(tornado.web.RequestHandler):
    def get(self,cid):
        self.write('<h1>享學課堂-當前課程ID:%d</h1>' %(int(cid)) )
        self.write(self.reverse_url('course',cid))

四、錯誤處理

1.使用write_error()方法

2.使用set_status()方法

3.使用tornado.web.HTTPError(error_code)丟擲異常

4.自定義錯誤

import tornado.ioloop
import tornado.web
import tornado.httpserver
import tornado.options
from tornado.options import define, options

define('port', type=int, default=8080)


class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.write("<h1>享學課堂-Tornado教程</h1>")


class test1Handler(tornado.web.RequestHandler):
    def get(self):
        self.write_error(404)
class test2Handler(tornado.web.RequestHandler):
    def get(self):
        self.write_error(500)
class test3Handler(tornado.web.RequestHandler):
    def get(self):
        self.set_status(500)
class Test4Handler(tornado.web.RequestHandler):
    def get(self):
        #raise tornado.web.HTTPError(404)
        raise tornado.web.HTTPError(status_code=404, log_message='test', reason='Not found page!')
class ErrorHandler(tornado.web.RequestHandler):
    def get(self):
        self.write('<h3 style="color:red">無效地址!</h3>')
urls=[
    (r'/',MainHandler),
    (r'/test1',test1Handler),
    (r'/test2',test2Handler),
    (r'/test3',test3Handler),
    (r'/test4',Test4Handler),
    (r'/test5',ErrorHandler)
]
#建立配置-開啟除錯模式
configs = dict(debug=True)
#自定義應用
class MyApplication(tornado.web.Application):
    def __init__(self, urls, configs):
        super(MyApplication, self).__init__(handlers=urls, **configs)



#建立伺服器
def make_app():
    tornado.options.parse_command_line()
    http_server = tornado.httpserver.HTTPServer(MyApplication(urls,configs))
    http_server.listen(options.port)
    tornado.ioloop.IOLoop.current().start()

#啟動伺服器
if __name__ == '__main__':
    make_app()

五、請求與響應

1.獲得請求引數:

獲得單個查詢引數

使用RequestHandler的get_argument()或者get_query_argument()可以獲得請求的單個引數。

class CourseHandler(tornado.web.RequestHandler):
    def get(self):
        self.write("<h1>享學課堂-Tornado教程</h1>")
        # arg = self.get_argument('name', default=None)
        arg = self.get_query_argument('name', default=None)
        self.write('引數是:%s' % arg)
# 路由
urls = [
    (r"/", MainHandler),
    (r"/course", CourseHandler),
]
 
# 訪問
# http://localhost:8080/course?name=Python3

2.獲得多個查詢引數

使用RequestHandler的get_arguments()或者get_query_arguments()可以獲得請求的多個引數。

class CourseHandler2(tornado.web.RequestHandler):
    def get(self):
        self.write("<h1>享學課堂-Tornado教程</h1>")
        # arg = self.get_arguments('name')
        arg = self.get_query_arguments('name')
        self.write('引數是:%s' % arg)
# 路由
urls = [
    (r"/", MainHandler),
    (r"/course2", CourseHandler2),
]
# 訪問
# http://localhost:8080/course2?name=1&name=2&name=100

3.獲得表單引數

使用RequestHandler的get_argument()/get_arguments()或者get_query_argument()/get_query_arguments()可以獲得請求的表單引數。

class LoginHandler(tornado.web.RequestHandler):
    def get(self):
        html = """
        <!DOCTYPE html>
        <html lang="en">
        <head>
          <meta charset="UTF-8">
          <title>享學課堂-使用者登入</title>
        </head>
        <body>
          <h1>享學課堂-使用者登入</h1>
          <hr>
 
          <form action="login" method="post">
          使用者名稱稱:<input type="text" name="username"/><br>
          使用者密碼:<input type="password" name="password"/><br>
          <input type="submit" value="登入"/><br>
          </form>
 
        </body>
        </html>
        """
        self.write(html)
 
    def post(self):
        username = self.get_argument('username', None)
        pwd = self.get_argument('password', None)
        print(username)
        print(pwd)
        self.write('使用者名稱稱:%s<br>密碼:%s' % (username, pwd))
 
# 路由
urls = [
    (r"/", MainHandler),
    (r"/login", LoginHandler),
]

4.設定響應內容型別:

可以使用RequestHandler.set_header(name,value)方法設定資訊頭來設定響應內容型別。

(1)設定輸出為html型別

class TestHtmlHandler(tornado.web.RequestHandler):
    def get(self):
        self.set_header('content-type', 'text/html')
        html = """
        <!DOCTYPE html>
        <html lang="en">
        <head>
          <meta charset="UTF-8">
          <title>享學課堂</title>
        </head>
        <body>
          <h1>享學課堂</h1>
          <hr>
          <p>享學課堂,愛學習,更愛分享!</p>
        </body>
        </html>
        """
        self.write(html)
 
# 路由
urls = [
    (r"/", MainHandler),
    (r"/html", TestHtmlHandler),
]

(2)設定輸出型別為xml

class TestXmlHandler(tornado.web.RequestHandler):
    def get(self):
        self.set_header('content-type', 'text/xml')
        xml = """
        <courselist>
          <course><name>Python</name></course>
          <course><name>Django</name></course>
          <course><name>Flask</name></course>
        </courselist>
        """
        self.write(xml)
 
# 路由
urls = [
    (r"/", MainHandler),
    (r"/xml", TestXmlHandler),

(3)設定輸出型別為json

class TestJsonHandler(tornado.web.RequestHandler):
 
    def get(self):
        self.set_header('content-type', 'application/json')
        dic = {'name':'享學課堂', 'site':'2xkt.com', 'course':'Tornado'}
        self.write(json.dumps(dic, ensure_ascii=False))
 
# 路由
urls = [
    (r"/", MainHandler),
    (r"/json", TestJsonHandler),
]

六、請求重定向

1.使用RequestHandler.redirect()方法進行重定向

class XXKTHandler(tornado.web.RequestHandler):
    def get(self):
        self.redirect('http://www.2xkt.com')
 
# 路由
urls = [
    (r"/", MainHandler),
    (r"/xxkt", XXKTHandler),
]

2.使用tornado.web.RedirectHandler進行重定向

直接在路由表裡配置

urls = [
    (r"/", MainHandler),
    (r"/easy", tornado.web.RedirectHandler, dict(url='http://www.163.com')),
]

3.使用重定向方法下載檔案

class DownloadHandler(tornado.web.RequestHandler):
    def get(self):
        url = 'https://github.com/tornadoweb/tornado/archive/master.zip'
        self.redirect(url)

urls = [
    (r'/download',DownloadHandler)]