1. asypost
  2. Sina weibo

Commits

asypost  committed 67d07d1

实现异步调用

  • Participants
  • Parent commits 90827f5
  • Branches master

Comments (0)

Files changed (2)

File core/decorators.py

View file
 import os
 import logging
 import functools
+from threading import Thread
 
 def view(template):
     def dec(func):
         logger.debug(message)
         return func(*args,**kwargs)
     return _
+
+try:
+    from gi.repository import GLib
+    idle_add=GLib.idle_add
+except:
+    try:
+        import gtk
+        idle_add=gtk.idle_add
+    except:
+        idle_add=None
+
+if idle_add:
+    def async(callback):
+        @functools.wraps(callback)
+        def _(func):
+            @functools.wraps(func)
+            def __(*args,**kwargs):
+                worker=Thread()
+                worker.setDaemon(True)
+                def run():
+                    return idle_add(callback,func(*args,**kwargs))
+                worker.run=run
+                worker.start()
+            return __
+        return _
+else:
+    def async(callback):
+        @functools.wraps(callback)
+        def _(func):
+            @functools.wraps(func)
+            def __(*args,**kwargs):
+                return callback(func(*args,**kwargs))
+            return __
+        return _

File core/weibo.py

View file
 import logging
 from bases import URIHandler,Request
 import json
+from decorators import async,debug
 
 logger=logging.getLogger("Weibo")
 
         if self.is_support(uri):
             request=Request.from_uri(uri)
             for client in self.__clients.values():
-                data=client.do_request(request)
-                self.pending_response(request.id,data)
+                #data=client.do_request(request)
+                #self.pending_response(request.id,data)
+                async(self.pending_response_callback)(self.handle_request_async)(client,request)
             return True
         return False
 
+    def handle_request_async(self,client,request):
+        data=client.do_request(request)
+        return request.id,data
+
+    def pending_response_callback(self,response):
+        self.pending_response(*response)
+
     def is_support(self,uri):
         ret=uri.lower().startswith(self.protocol)
         ret or logger.warn("Unsupport URI:{0}".format(uri))