輸入輸出:html
class MainHandler(RequestHandler): def get(self): self.write('hello world') self.write(123) #這一行會報錯
報錯信息以下:web
TypeError: write() only accepts bytes, unicode, and dict objectsjson
輸入輸出:
輸出:
write能寫的幾種格式 bytes, unicode, and dict objects
bytes
字符串
字典
json
flush
渲染模板render 添加模板位置templates
路由跳轉redirect
結束:finish瀏覽器
class MainHandler(RequestHandler): def get(self): self.write('hello world') self.write('<br/>') self.write(b'hello world') #bytes self.write('<br/>') # self.write(123) #報錯 self.flush() #強制吧緩衝區的內容刷新到瀏覽器 di = { 'name': 'shiwei', 'age': 23 } self.write(di) # dictory #當write方法向瀏覽器輸出字典的時候,其餘全部的格式都不被解析, #當瀏覽器輸出字典時候,其餘的所有被當成json字符串的一部分輸出 li = ['taka',52] # self.write(li) #列表也不能寫入 self.write(str(li)) #將列表轉換成字符串 li = json.dumps(li) #轉換成json的字符串 self.write(li) self.finish() self.write('1111') #調用finish以後,不會輸出到瀏覽器上,代碼依然會被執行性 # 報錯raise RuntimeError("Cannot write() after finish()") #字節格式,字符串,字典 #b'hello' 字節 #'hello' #{'name':'shiwei'} class TemHandler(RequestHandler): def get(self): self.render('in_out.html') #將頁面寫到一個文件裏面,當咱們訪問這個路由的時候讀取文件 class RedHandler(RequestHandler): def get(self): time.sleep(5) self.redirect('/tem') application = tornado.web.Application( handlers=[ (r'/', MainHandler), (r'/tem', TemHandler), (r'/red', RedHandler), ], template_path = 'templates', #指定靜態模板的文件夾 debug=True #方便調試 )
獲取請求信息app
class ReqHandler(RequestHandler): def get(self): print(self.request) self.write(self.request.remote_ip) application = tornado.web.Application( handlers=[ (r'/req', ReqHandler), ], template_path = 'templates', #指定靜態模板的文件夾 debug=True #方便調試 )
self.request中包含全部的請求信息:tornado
能夠使用的方法:post
輸入:spa
get_argument只能獲取輸入的最後一個參數,調用了get_arguments,而且取列表的最後一個元素,獲取 URL 和 Body中數據debug
get_arguments 獲取輸入的列表,複選框的時候使用調試
-- 獲取URL數據
get_argument
能夠獲取URL(查詢字符串)中的參數
-- 獲取body數據
get_argument
能夠獲取body(請求體)中的數據
get_argument返回的值始終是unicode
02-input_output.py
class GetHandler(RequestHandler): def get(self): self.render('in_out.html') def post(self): # name = self.get_argument('name','') name = self.get_body_argument('name','') self.write(name) self.write('<br/>') password = self.get_argument('password','') self.write(password) application = tornado.web.Application( handlers=[ (r'/get', GetHandler), ],
in_out.html代碼:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>tornado</title> </head> <body> <form method="post" action="/get"> <p>用戶名<input type="text" name="name"></p> <p>密碼<input type="password" name="password"></p> <input type="submit"> </form> </body> </html>
URL傳參
1.REST風格查詢
class SubHandler(RequestHandler): def get(self,name,age): self.write('name:%s <br/> age:%s'%(name,age)) application = tornado.web.Application( handlers=[ (r'/sub/(?P<name>.+)/(?P<age>[0-9]+)', SubHandler), ],
請求結果以下:
2.字符串風格,?key=value
class SubHandler(RequestHandler): def get(self): name = self.get_argument('name','')
self.write(name)
application = tornado.web.Application( handlers=[ (r'/sub/', SubHandler), ],
請求結果以下: