diff pyikriam/__init__.py @ 160:7551342718b6

Refactory pyikriam with patterns. - Use dyna_prog, a dynamic programming decorator, to cache city objects. - fake_moz to emulate a mozilla browser.
author Thinker K.F. Li <thinker@branda.to>
date Sat, 01 Nov 2008 21:29:51 +0800
parents 19d2a7b175b3
children 1507c2d16b35
line wrap: on
line diff
--- a/pyikriam/__init__.py	Sat Nov 01 16:38:56 2008 +0800
+++ b/pyikriam/__init__.py	Sat Nov 01 21:29:51 2008 +0800
@@ -4,23 +4,44 @@
 import os
 import urllib2
 import urllib
+from utils import dyna_prog, decorator
+
+class fake_moz(object):
+    __metaclass__ = decorator
+
+    def __init__(self):
+        super(fake_moz, self).__init__()
+        cookie_jar = cookielib.LWPCookieJar()
+        cookie_proc = urllib2.HTTPCookieProcessor(cookie_jar)
+        opener = urllib2.build_opener(cookie_proc)
+        opener.addheaders = [('User-agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-TW; rv:1.8.1.12pre) Gecko/20071220 BonEcho/2.0.0.12pre')]
+        fake_moz.set_backend(self, opener)
+        self.cookie_jar = cookie_jar
+        pass
+    pass
+
+
 class Ikariam:
 
     cities = {}
+    COOKIEFILE = '/tmp/ikariam.lwp'
 
     def __init__(self):
-        self.COOKIEFILE = '/tmp/ikariam.lwp'
+        browser = fake_moz()
+        self.browser = browser
+        self._cookie_jar = browser.cookie_jar
+
+        if os.path.isfile(self.COOKIEFILE):
+            self._cookie_jar.load(self.COOKIEFILE)
+            pass
+ 
+        urllib2.install_opener(browser)
+
 	self.confdata=LoadConfigfile().cd
         self.baseurl='http://'+self.confdata['server']
-        self.cj = cookielib.LWPCookieJar()
-        if os.path.isfile(self.COOKIEFILE):
-            self.cj.load(self.COOKIEFILE)
- 
-        opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cj))
-        opener.addheaders = [('User-agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-TW; rv:1.8.1.12pre) Gecko/20071220 BonEcho/2.0.0.12pre')]
-        urllib2.install_opener(opener)
 
         self.login()
+        pass
 
     def login(self):     
 	print "login to %s...." % self.confdata['server']
@@ -28,16 +49,23 @@
         "name":self.confdata['user'], \
         "password":self.confdata['pass']}
         ret = c(self.baseurl+'/index.php?action=loginAvatar&function=login').get(params).get_content()
-        self.cj.save(self.COOKIEFILE)
-        
+        self._cookie_jar.save(self.COOKIEFILE)
+        pass
+
     def logout(self):
 	print "logut from %s...." % self.confdata['server']
         c(self.baseurl+'/index.php?action=loginAvatar&function=logout')
         os.remove(self.COOKIEFILE)
-        
+        pass
+    
+    ##
+    # \note We can cache data with decorator 'dynamic programming'.
+    #
+    @dyna_prog
     def city(self, id):
-	return self.cities.get(id, IkariamCity(id=id, core=self) )
-    
+        return IkariamCity(id=id, core=self)
+    pass
+
 class IkariamCity:
     
     def __init__(self, id, core ):