1、快速瞭解Tornado框架javascript
1)tornado簡介css
Tornado 和如今的主流 Web 服務器框架(包括大多數 Python 的框架)有着明顯的區別:它是非阻塞式服務器,並且速度至關快。得利於其 非阻塞的方式和對epoll的運用,Tornado 每秒能夠處理數以千計的鏈接,所以 Tornado 是實時 Web 服務的一個 理想框架。咱們開發這個 Web 服務器的主要目的就是爲了處理 FriendFeed 的實時功能 ——在 FriendFeed 的應用裏每個活動用戶都會保持着一個服務器鏈接 FriendFeed是一個聚合我的信息的網站,可集成網絡社區媒體、社交網絡服務、書籤網站、博客、微博客的更新,及其餘RSS/Atom信源 安裝 pip install tornado
2)tornado框架快速上手html
import tornado.ioloop import tornado.web class MainHandler(tornado.web.RequestHandler): def get(self): self.write("Hello, world") application = tornado.web.Application([ (r"/index", MainHandler), ]) if __name__ == "__main__": application.listen(8888) tornado.ioloop.IOLoop.instance().start()
執行過程前端
1:執行腳本,監聽 8888 端口 2:瀏覽器客戶端訪問 /index --> http://127.0.0.1:8888/index 3:服務器接受請求,並交由對應的類處理該請求 4:類接受到請求以後,根據請求方式(post / get / delete ...)的不一樣調用並執行相應的方法 5:方法返回值的字符串內容發送瀏覽器
#!/usr/bin/env python # -*- coding:utf-8 -*- import tornado.ioloop import tornado.web from tornado import httpclient from tornado.web import asynchronous from tornado import gen import uimodules as md import uimethods as mt class MainHandler(tornado.web.RequestHandler): @asynchronous @gen.coroutine def get(self): print 'start get ' http = httpclient.AsyncHTTPClient() http.fetch("http://127.0.0.1:8008/post/", self.callback) self.write('end') def callback(self, response): print response.body settings = { 'template_path': 'template', 'static_path': 'static', 'static_url_prefix': '/static/', 'ui_methods': mt, 'ui_modules': md, } application = tornado.web.Application([ (r"/index", MainHandler), ], **settings) if __name__ == "__main__": application.listen(8009) tornado.ioloop.IOLoop.instance().start()
2、tornado的模板語言java
1)git請求,返回前端頁面。rendernode
import tornado.ioloop import tornado.web class LoginHandler(tornado.web.RequestHandler): def get(self): self.render('login.html') def post(self): self.write("Hello, world") # 生成路由規則 application = tornado.web.Application([ (r"/login", LoginHandler), ]) if __name__ == "__main__": # 建立socket對象8888 # 將socket對象添加到select或epoll application.listen(8888) # 將select或epoll開始死循環 while True tornado.ioloop.IOLoop.instance().start()
前端頁面默認同級目錄python
2)前端模板顯示內容mysql
import tornado.ioloop import tornado.web class LoginHandler(tornado.web.RequestHandler): def get(self): # self.render('login.html') # self.render('login.html',k1='v1') # self.render('login.html',k1='v1',k2='v2') # self.render('login.html',**{'k1':'v1'}) self.render('login.html',**{'k1':'v1', 'k2':[1,2,3,4], 'k3':{'name':'root','age':18}}) # 生成路由規則 application = tornado.web.Application([ (r"/login", LoginHandler), ]) if __name__ == "__main__": # 建立socket對象8888 # 將socket對象添加到select或epoll application.listen(8888) # 將select或epoll開始死循環 while True tornado.ioloop.IOLoop.instance().start()
對於前端顯示git
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>Login</h1> <h3>{{k1}}</h3> <h2>{{k2}}</h2> <h2>{{k2[0]}}</h2> <ul> {% for item in k2 %} <li>{{item}}</li> {%end%} </ul> <div>{{k3}}</div> <div>{{k3['name']}}</div> <div>{{k3.get('name')}}</div> <ul> {% for k,v in k3.items() %} <li>{{k}}--{{v}}</li> {%end%} </ul> </body> </html>
前端語法經常使用概括web
{% for item in k2 %} <li>{{item}}</li> {%end%} <h2>{{k2}}</h2> <h2>{{k2[0]}}</h2> <div>{{k3['name']}}</div> <div>{{k3.get('name')}}</div>
3)獲取用戶相應信息
def get(self): # 獲取用戶請求相關信息 self.get_cookie() v = self.get_argument('p') # http://127.0.0.1:8888/login?p=123 print(v) self.render('login.html',**{'k1':'v1', 'k2':[1,2,3,4], 'k3':{'name':'root','age':18}})
有多個self,也返回給用戶
4)self.set_cookies。設置額外的內容
def get(self): # 設置額外的相應內容 self.set_cookie('k1','v1') # 設置cookies self.set_header('h1','v1') # 設置相應頭 self.render('login.html')
5)跳轉。self.redirect('/login/')
6)靜態文件和模板文件的配置
settings = { 'static_path':'static', 'static_url_prefix':'/sss/', 'template_path':'templates', } application = tornado.web.Application([ (r"/login", LoginHandler), ],**settings)
前端文件引入靜態文件
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheet" href="/sss/commons.css"> </head> <body> <h1>Login</h1> </body> </html>
7)後臺獲取form表單提交的數據
<form method="POST" action="/login"> <input type="text" name="user"> <input type="submit" value="提交"> </form>
class LoginHandler(tornado.web.RequestHandler): def get(self): self.render('login.html') def post(self): v = self.get_argument('user') print(v) self.redirect('http://autohome.com.cn')
8)自定義函數註冊,前端執行函數
def tab(self): return 'UIMethod'
settings字典註冊
import uimethods as mt settings = { 'static_path':'static', 'static_url_prefix':'/sss/', 'template_path':'templates', 'ui_methods':mt, } application = tornado.web.Application([ (r"/login", LoginHandler), ],**settings)
前端調用函數
<body> <h1>Login {{ tab() }}</h1> <form method="POST" action="/login"> <input type="text" name="user"> <input type="submit" value="提交"> </form> </body>
9)自定義類方法註冊。可返還通常數據,css樣式,css文件,js文件
from tornado.web import UIModule from tornado import escape class Custom(UIModule): def embedded_css(self): return "body{color:blue;}" def css_files(self): return "a.sss" def javascript_files(self): return "a.js" def render(self, *args, **kwargs): return '<h1>user sb</h1>' #return escape.xhtml_escape('<h1>user sb</h1>')
settings字典註冊
import uimethods as mt import uimodules as md settings = { 'static_path':'static', 'static_url_prefix':'/sss/', 'template_path':'templates', 'ui_methods':mt, 'ui_modules':md, }
前端調用函數
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheet" href="/sss/commons.css"> </head> <body> <h1>Login {{ tab() }}</h1> <h2>{% module Custom(123) %}</h2> <form method="POST" action="/login"> <input type="text" name="user"> <input type="submit" value="提交"> </form> </body> </html>
3、tornado的session管理
1)基於內存的session
session文件方法
import uuid class Session(object): container = {} def __init__(self,handler): # 獲取用戶cookies,若是有,不操做,不然給用戶生成隨機字符串 # - 寫給用戶 # - 保存在session nid = handler.get_cookie('session_id') if nid: if nid in Session.container: pass else: nid = str(uuid.uuid4()) Session.container[nid] = {} else: nid = str(uuid.uuid4()) Session.container[nid] = {} handler.set_cookie('session_id',nid,max_age=1000) # max_age=1000 超時時間 # nid 當前訪問用戶的隨機字符串+ self.nid = nid # 封裝了全部用戶請求信息 self.handler = handler def __setitem__(self,key,value): Session.container[self.nid][key] = value def __getitem__(self,item): return Session.container[self.nid].get(item) def __delitem__(self, key): del Session.container[self.nid][key]
驗證session的類
import tornado.ioloop import tornado.web class BaseHandler(object): def initialize(self): from session import Session self.session = Session(self) super(BaseHandler,self).initialize() class IndexHandler(BaseHandler,tornado.web.RequestHandler): def get(self): if self.session['is_login']: self.write('Hello World') else: self.redirect('/login') class LoginHandler(BaseHandler,tornado.web.RequestHandler): def get(self): self.render('login.html') def post(self): v = self.get_argument('user') if v == 'root': self.session['is_login'] = True self.redirect('/index') else: self.redirect('/login')
總的運行文件
import tornado.ioloop import tornado.web class BaseHandler(object): def initialize(self): from session import Session self.session = Session(self) super(BaseHandler,self).initialize() class IndexHandler(BaseHandler,tornado.web.RequestHandler): def get(self): if self.session['is_login']: self.write('Hello World') else: self.redirect('/login') class LoginHandler(BaseHandler,tornado.web.RequestHandler): def get(self): self.render('login.html') def post(self): v = self.get_argument('user') if v == 'root': self.session['is_login'] = True self.redirect('/index') else: self.redirect('/login') settings = { 'static_path':'static', 'static_url_prefix':'/sss/', 'template_path':'templates', } application = tornado.web.Application([ (r"/login", LoginHandler), (r"/index", IndexHandler), ],**settings) if __name__ == "__main__": application.listen(8888) tornado.ioloop.IOLoop.instance().start()
2)基於redis的session
class RedisSession(object): def __init__(self,handler): # 獲取用戶cookies,若是有,不操做,不然給用戶生成隨機字符串 # - 寫給用戶 # - 保存在session nid = handler.get_cookie('session_id') if nid: if nid in Session.container: pass else: nid = str(uuid.uuid4()) # Session.container[nid] = {} # 鏈接redis寫值 else: nid = str(uuid.uuid4()) # Session.container[nid] = {} # 鏈接redis寫值 handler.set_cookie('session_id',nid,max_age=1000) # max_age=1000 超時時間 # nid 當前訪問用戶的隨機字符串+ self.nid = nid # 封裝了全部用戶請求信息 self.handler = handler def __setitem__(self,key,value): # Session.container[self.nid][key] = value pass def __getitem__(self,item): # return Session.container[self.nid].get(item) pass def __delitem__(self, key): # del Session.container[self.nid][key] pass
3)設置配置文件,選擇使用哪一種session
新建配置文件文件
session_key = "RedisSession"
經過getattr方法找到config文件內容
import config class BaseHandler(object): def initialize(self): import session cls = getattr(session,config.session_key) self.session = cls(self) super(BaseHandler,self).initialize()
4)補充,根據算法,計算選擇哪臺機器,可設置機器的權重來分配機器的任務量
#__author: Administrator #date: 2017/3/10 import sys import math from bisect import bisect if sys.version_info >= (2, 5): import hashlib md5_constructor = hashlib.md5 else: import md5 md5_constructor = md5.new class HashRing(object): """一致性哈希""" def __init__(self, nodes): '''初始化 nodes : 初始化的節點,其中包含節點已經節點對應的權重 默認每個節點有32個虛擬節點 對於權重,經過多建立虛擬節點來實現 如:nodes = [ {'host':'127.0.0.1:8000','weight':1}, {'host':'127.0.0.1:8001','weight':2}, {'host':'127.0.0.1:8002','weight':1}, ] ''' self.ring = dict() self._sorted_keys = [] self.total_weight = 0 self.__generate_circle(nodes) def __generate_circle(self, nodes): for node_info in nodes: self.total_weight += node_info.get('weight', 1) for node_info in nodes: weight = node_info.get('weight', 1) node = node_info.get('host', None) virtual_node_count = math.floor((32 * len(nodes) * weight) / self.total_weight) for i in range(0, int(virtual_node_count)): key = self.gen_key_thirty_two('%s-%s' % (node, i)) if self._sorted_keys.__contains__(key): raise Exception('該節點已經存在.') self.ring[key] = node self._sorted_keys.append(key) def add_node(self, node): ''' 新建節點 node : 要添加的節點,格式爲:{'host':'127.0.0.1:8002','weight':1},其中第一個元素表示節點,第二個元素表示該節點的權重。 ''' node = node.get('host', None) if not node: raise Exception('節點的地址不能爲空.') weight = node.get('weight', 1) self.total_weight += weight nodes_count = len(self._sorted_keys) + 1 virtual_node_count = math.floor((32 * nodes_count * weight) / self.total_weight) for i in range(0, int(virtual_node_count)): key = self.gen_key_thirty_two('%s-%s' % (node, i)) if self._sorted_keys.__contains__(key): raise Exception('該節點已經存在.') self.ring[key] = node self._sorted_keys.append(key) def remove_node(self, node): ''' 移除節點 node : 要移除的節點 '127.0.0.1:8000' ''' for key, value in self.ring.items(): if value == node: del self.ring[key] self._sorted_keys.remove(key) def get_node(self, string_key): '''獲取 string_key 所在的節點''' pos = self.get_node_pos(string_key) if pos is None: return None return self.ring[self._sorted_keys[pos]].split(':') def get_node_pos(self, string_key): '''獲取 string_key 所在的節點的索引''' if not self.ring: return None key = self.gen_key_thirty_two(string_key) nodes = self._sorted_keys pos = bisect(nodes, key) return pos def gen_key_thirty_two(self, key): m = md5_constructor() m.update(bytes(key,encoding='utf-8')) return int(m.hexdigest(), 16) def gen_key_sixteen(self, key): b_key = self.__hash_digest(key) return self.__hash_val(b_key, lambda x: x) def __hash_val(self, b_key, entry_fn): return ( (b_key[entry_fn(3)] << 24) | (b_key[entry_fn(2)] << 16) | (b_key[entry_fn(1)] << 8) | b_key[entry_fn(0)]) def __hash_digest(self, key): m = md5_constructor() m.update(bytes(key, encoding='utf-8')) return map(ord, m.digest()) nodes = [ {'host':'127.0.0.1:8000','weight':5}, {'host':'127.0.0.1:8001','weight':1}, {'host':'127.0.0.1:8002','weight':5}, ] ring = HashRing(nodes) result = ring.get_node('asdfasdfasdf') print(result)
4、form驗證,生成html標籤
1)自定義版本form驗證
import tornado.web import re class StringField: def __init__(self,name): self.rex = "^\w+$" self.name = name self.value = '' self.error = "" def __str__(self): return "<input type='text' name='%s' value='%s' />" %(self.name,self.value,) class EmailField: def __init__(self,name): self.rex = "^\w+@.*$" self.name = name self.value = '' self.error = "" def __str__(self): return "<input type='text' name='%s' value='%s' />" %(self.name,self.value,) class LoginForm: def __init__(self): self.user = StringField(name='user') self.email = EmailField(name='email') def is_valid(self,handler): value_dict = {} flag = True for k,v in self.__dict__.items(): inp = handler.get_argument(k) # 1: k=user, inp='asdf' v ="\w+" => StringField(name='user') # 1: k=email, inp='asdfasdf' v ="^\w+@.*$" => EmailField(name='email') rex = re.match(v.rex,inp) v.value = inp if rex: value_dict[k] = inp else: v.error = '%s 錯誤了..' %k flag = False return flag,value_dict class LoginHandler(tornado.web.RequestHandler): def get(self, *args, **kwargs): obj = LoginForm() self.render('login.html',**{'obj': obj}) def post(self, *args, **kwargs): obj = LoginForm() valid,value_dict = obj.is_valid(self) print(valid,value_dict) if valid: print(value_dict) else: return self.render('login.html',**{'obj': obj}) settings = { 'static_path': 'static', 'static_url_prefix': '/sss/', 'template_path':'templates', } application = tornado.web.Application([ (r"/login", LoginHandler), ],**settings) if __name__ == "__main__": application.listen(8888) tornado.ioloop.IOLoop.instance().start()
5、pymysql鏈接數據庫測試登陸版本的tornado
#!/usr/bin/env python #-*-coding: utf-8 -*- import tornado.ioloop import tornado.web import pymysql class MainHandler(tornado.web.RequestHandler): def get(self): #get 和 post的區別,get,url中傳輸數據 self.render("login.html") def post(self, *args, **kwargs): # 獲取用戶提交的數據a username = self.get_argument('username', None) # 獲取數據,經過,get_argument pwd = self.get_argument('pwd', None) # 建立數據庫鏈接 conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='', db='db1') cursor = conn.cursor() # temp = "select name from userinfo where name='%s' and password = '%s'" % (username, pwd) # 不安全 # print(temp) effect_row = cursor.execute("select name from userinfo where name= %s and password = %s ", (username, pwd,)) #安全些 result = cursor.fetchone() conn.commit() cursor.close() conn.close() if result: self.write('登陸成功') else: self.write('登陸失敗') settings = { "template_path":"template", # 模板路徑 'static_path': 'static', # 靜態文件的處理,即對css文件的處理 'static_url_prefix': '/static/', # 靜態文件的前綴 } # 路由映射,路由系統 application = tornado.web.Application([ (r"/login", MainHandler), # ==》login.html ],**settings) if __name__ == "__main__": application.listen(8888) tornado.ioloop.IOLoop.instance().start()
2. login.html 文件
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/login" method="post"> <input type="text" name="username" placeholder="用戶" /> <input type="text" name="pwd" placeholder="密碼" /> <input type="submit" /> </form> </body> </html>
3、在tornado中定義模板路徑
在模板中默認提供了一些函數、字段、類以供模板使用:
escape
: tornado.escape.xhtml_escape
的別名xhtml_escape
: tornado.escape.xhtml_escape
的別名url_escape
: tornado.escape.url_escape
的別名json_encode
: tornado.escape.json_encode
的別名squeeze
: tornado.escape.squeeze
的別名linkify
: tornado.escape.linkify
的別名datetime
: Python 的 datetime
模組handler
: 當前的 RequestHandler
對象request
: handler.request
的別名current_user
: handler.current_user
的別名locale
: handler.locale
的別名_
: handler.locale.translate
的別名static_url
: for handler.static_url
的別名xsrf_form_html
: handler.xsrf_form_html
的別名Tornado默認提供的這些功能其實本質上就是 UIMethod 和 UIModule,咱們也能夠自定義從而實現相似於Django的simple_tag的功能:
一、定義
def tab(self): return 'UIMethod'
#!/usr/bin/env python # -*- coding:utf-8 -*- from tornado.web import UIModule from tornado import escape class custom(UIModule): def render(self, *args, **kwargs): return escape.xhtml_escape('<h1>user</h1>') #return escape.xhtml_escape('<h1>user</h1>')
二、註冊
#!/usr/bin/env python # -*- coding:utf-8 -*- import tornado.ioloop import tornado.web from tornado.escape import linkify import uimodules as md import uimethods as mt class MainHandler(tornado.web.RequestHandler): def get(self): self.render('index.html') settings = { 'template_path': 'template', 'static_path': 'static', 'static_url_prefix': '/static/', 'ui_methods': mt, 'ui_modules': md, } application = tornado.web.Application([ (r"/index", MainHandler), ], **settings) if __name__ == "__main__": application.listen(8009) tornado.ioloop.IOLoop.instance().start()
三、使用
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> <link href="{{static_url("commons.css")}}" rel="stylesheet" /> </head> <body> <h1>hello</h1> </body> </html>
4、關於tornado的cookie的認識
cookie值便是用戶登陸系統後全部產生的cookie值,保留這種用戶的客戶端,再次登陸只須要驗證cookie值,就可登陸成功
一、定義一個首頁
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>首頁</h1> </body> </html>
二、定義登陸頁
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/login" method="post"> <input type="text" name="username" /> <input type="password" name="password" /> <input type="submit" value="登陸" /> <span style="color: red">{{status_text}}</span> </form> </body> </html>
三、定義登陸後才見到的頁面
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <a href="/logout">退出</a> <h1>銀行卡餘額1000</h1> </body> </html>
四、主程序。邏輯關係的呈現
#!/usr/bin/env python #-*-coding: utf8-*- # 項目一,關於cookis的認識 # viems文件夾 # index.html 主頁 # login.html 登陸頁 # manager.html 登陸能看的頁 # __init__.py # runmain.py import tornado.ioloop import tornado.web # 定義首頁 class IndexHandler(tornado.web.RequestHandler): def get(self,*args,**kwargs): self.render('index.html',) # 定義須要登陸才能看到的頁面,即須要有cookie class ManagerHandler(tornado.web.RequestHandler): def get(self,*args,**kwargs): co = self.get_cookie('auth') if co == '1': self.render('manager.html',) else: self.redirect("/login") # 定義登陸後出現的退出程序 class LogoutHandler(tornado.web.RequestHandler): def get(self, *args, **kwargs): self.get_cookie('auth','0') self.render('/login' ) # 定義登陸頁,若是成功,則產生cookie class LoginHandler(tornado.web.RequestHandler): def get(self,*args,**kwargs): self.render('login.html',status_text="") def post(self, *args, **kwargs): username = self.get_argument('username',None) pwd = self.get_argument('password',None) if username == 'user' and pwd == "sb": self.set_cookie('auth','1') self.redirect('/manager') else: self.render('login.html',status_text="登陸失敗") settings = { 'template_path':'viems', } application = tornado.web.Application([ (r"/index", IndexHandler), (r"/login", LoginHandler), (r"/manager", ManagerHandler), (r"/logout",LogoutHandler) ], **settings) if __name__ == "__main__": application.listen(8888) tornado.ioloop.IOLoop.instance().start()
運行程序,檢驗其邏輯關係,各個頁面。127.0.0.1:8888/index ,127.0.0.1:8888/login,各個cookie值
五、補充cookie保存的時間,增長cookie值帶的用戶名
class LoginHandler(tornado.web.RequestHandler): def get(self,*args,**kwargs): self.render('login.html',status_text="") def post(self, *args, **kwargs): username = self.get_argument('username',None) pwd = self.get_argument('password',None) check = self.get_argument('auto',None) if username == 'user' and pwd == "sb": if check: self.set_cookie('username',username,expires_days=7) self.set_cookie('auth','1',expires_days=7) else: r = time.time() + 100 self.set_cookie('auth','1',expires=r) self.set_cookie('username', username, expires=r) self.redirect('/manager') else: self.render('login.html',status_text="登陸失敗")
<body> <form action="/login" method="post"> <input type="text" name="username" /> <input type="password" name="password" /> <input type="checkbox" name="auto" value="1" />7天免登陸 <input type="submit" value="登陸" /> <span style="color: red">{{status_text}}</span> </form> </body>