顯示具有 asynchronous 標籤的文章。 顯示所有文章
顯示具有 asynchronous 標籤的文章。 顯示所有文章

2014/04/05

Coroutine in Tornado Web Framework

Coroutine 可以讓我們在程式中按照自己的意思去安排執行順序,有點像是 jump 的概念,它允許短暫離開 function 並且保留 local variable 的狀態,等到某個時間點再跳回來,從上一次離開的地方繼續。第一次接觸到 coroutine 的概念是從 python,coroutine 是一種語言特性,從 wiki 可以看到很多語言都有這種特性。

那我們沒事幹嘛讓程式跳來跳去的?思考一種狀況,當在 single thread 下,你執行到一個 blocking function,這時候如果讓 CPU 去做其他事情是不是很好,等到 I/O 有回應的,再跳回來原本的地方繼續執行。等等,這不就是 event-driven 的 programming 嗎?它們的表達方式還是有點區別。


舉一個例子,我們發出一個 HTTP request 去抓 Yahoo weather 的資訊,然後利用 XML parser 從回應得資料中取出溫度,以下是利用一般非同步的方式去撰寫:
from tornado.ioloop import IOLoop
from tornado.web import Application, RequestHandler, asynchronous
from tornado.httpclient import AsyncHTTPClient
from xml.dom import minidom

class MainHandler(RequestHandler):
    url = "http://weather.yahooapis.com/forecastrss?w=2306179&u=c"

    @asynchronous
    def get(self):
        http_client = AsyncHTTPClient()
        http_client.fetch(self.url, callback=self._on_fetch)

    def _on_fetch(self, response):
        degree = self._parse_xml(response.body)
        self.finish("Taipei: %d" % degree)

    def _parse_xml(self, xml):
        xml_doc = minidom.parseString(xml)
        weather_list = xml_doc.getElementsByTagName('yweather:condition')
        degree = float(weather_list[0].attributes['temp'].value)
        return degree

if __name__ == "__main__":
    application = Application([
        (r"/", MainHandler),
    ])
    application.listen(8888)
    IOLoop.instance().start()
第 12 行:在發出 request 同時指定 callback
第 14 行:在收到 server 回應後,執行 _on_fetch()


換成 coroutine 的方式
from tornado.ioloop import IOLoop
from tornado.web import Application, RequestHandler, asynchronous
from tornado.httpclient import AsyncHTTPClient
import tornado.gen as gen
from xml.dom import minidom

class MainHandler(RequestHandler):
    url = "http://weather.yahooapis.com/forecastrss?w=2306179&u=c"

    @gen.coroutine
    def get(self):
        http_client = AsyncHTTPClient()
        response = yield http_client.fetch(self.url)
        degree = self._parse_xml(response.body)
        self.finish("Taipei: %d" % degree)

    def _parse_xml(self, xml):
        xml_doc = minidom.parseString(xml)
        weather_list = xml_doc.getElementsByTagName('yweather:condition')
        degree = float(weather_list[0].attributes['temp'].value)
        return degree

if __name__ == "__main__":
    application = Application([
        (r"/", MainHandler),
    ])
    application.listen(8888)
    IOLoop.instance().start()
第 13 行:程式執行完 yield 後面的 statement 這個 function 就會立刻 return,直到 tornado io loop 收到 server 回應,然後跳回第 13 行,把 fetch() 的結果 assign 給 response,然後繼續執行下去。
底層一樣是非同步I/O,但這種表達方式擁有在寫同步 I/O 般的直覺。


單一個 callback 可能顯示不出直覺在哪裡,如果連存取 database/memcach... 任何跟I/O相關的事情都採用非同步方式,那就會需要在 callback 中執行另一個 callback
class MainHandler(RequestHandler):
    @tornado.web.asynchronous
    def get(self):
        req1(argument1, callback=self._res1)

    @tornado.web.asynchronous
    def _res1(self, response1):
        ...do something with response
        req2(argument2, callback=self._res2)

    def _res2(self, response2):
        ...do something with response
        self.finish("result...")

改用 coroutine 的方式
class MainHandler(RequestHandler):    
    @tornado.gen.coroutine
    def get(self):
        response1 = yield req1(argument1)
        ...do something with response1
        response2 = yield req2(argument2)
        ...do something with response2
        self.finish("result...")

是不是直覺很多!

2013/04/25

初次玩 Backbone.js: 多種 Template 的實作方式

假設我想設計一個公司資料,model 為單一員工資料,包含 id 與 name。collection 為部門資料,由多個員工所組成。而 view 用來顯示部門資料之用。
// Models
company.models.Employee = Backbone.Model.extend({
    defaults: {
        id: undefined,
        name: undefined
    }
});

// Collections
company.collections.Department = Backbone.Collection.extend({
    model: company.models.Employee
});

// Views
company.views.EmployeeList = Backbone.View.extend({
    el: "#container",
 
    render: function() {
        ...
    }
});

// Create base data
var c = new company.collections.Department(
        [{id:1, name: "Star Willard"},
         {id:2, name: "Rhona Eggleston"},
         {id:3, name: "Cassi Chowdhury"},
         {id:4, name: "Leigh Nilson"},
         {id:5, name: "Niesha Auger"}
        ]);

// Create view
var v = new company.views.EmployeeList({collection: c});
v.render();


以下就來探討 render function 該怎麼把 collection 套用到 template 並呈現在 UI 上

2013/04/23

WebSocket on Tornado

Tornado 一直是我愛用的 python web framework,這幾年工作上一直在寫 event-drivent socket programming,所以被它 non-blocking 的特性給深深吸引,如果每件 block 的工作都能用 asynchronous 的方式來解決,那程式執行的效率一定超好!


延續『WebSocket 雙向即時通訊 - 初探』,今天就以 Tornado 來寫個簡單的 WebSocket 範例。當 client 連到 server 後,會傳送 hello ,而 server 回應一樣的訊息,傳送到第五次,server 就把 client 斷掉。

Server (ws_server.py)
import tornado.ioloop
import tornado.web
from tornado import websocket


class WSHandler(websocket.WebSocketHandler):
    count = 0
    def open(self):
        print "Client connected"

    def on_message(self, msg):
        print "[%d] Got message [%s] from client" % (self.count, msg)
        if self.count == 4:
            self.close()
            return
        # Write back message
        self.write_message("[%d] Echo: %s" % (self.count, msg))
        self.count += 1

    def on_close(self):
        print "Client disconnected"


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

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



Client (ws_client.py)
from tornado.websocket import websocket_connect
from tornado.ioloop import IOLoop


class ws_client():
    conn = None # This is WebSocketClientConnection
    def __init__(self):
        websocket_connect('ws://localhost:8888/', callback=self.conn_cb)
        
    def conn_cb(self, future):
        self.conn = future.result()
        self.conn.write_message("hello")
        self.conn.read_message(self.read_cb)
        
    def read_cb(self, future):
        msg = future.result()
        if msg is None:
            print "Server disconnected"
            IOLoop.instance().stop()
        else:
            print msg
            self.conn.write_message("hello")
            self.conn.read_message(self.read_cb)

if __name__ == '__main__':
    ws_client()
    IOLoop.instance().start()