Commits

zuroc committed a4f77fb

f

  • Participants
  • Parent commits 1ae8dee

Comments (0)

Files changed (1)

.app/oauth/model/douban.py

+#coding:utf-8
+
+class DoubanMixin(tornado.auth.OAuthMixin):
+    _OAUTH_REQUEST_TOKEN_URL = 'http://www.douban.com/service/auth/request_token'
+    _OAUTH_ACCESS_TOKEN_URL = 'http://www.douban.com/service/auth/access_token'
+    _OAUTH_AUTHORIZE_URL = 'http://www.douban.com/service/auth/authorize'
+    _OAUTH_VERSION = '1.0'
+    _OAUTH_NO_CALLBACKS = False
+    _on_request = _on_request
+    callback_url = callback_url
+
+    def _request(self, path, callback, access_token=None,
+                           post_args=None, **args):
+        # Add the OAuth resource request signature if we have credentials
+        url = 'http://api.douban.com%s'%path
+        if access_token:
+            all_args = {}
+            all_args.update(args)
+            all_args.update(post_args or {})
+            consumer_token = self._oauth_consumer_token()
+            method = 'POST' if post_args is not None else 'GET'
+            oauth = self._oauth_request_parameters(
+                url, access_token, all_args, method=method)
+            args.update(oauth)
+        if args: url += '?' + urllib.urlencode(args)
+        callback = self.async_callback(self._on_request, callback)
+        http = httpclient.AsyncHTTPClient()
+        if post_args is not None:
+            http.fetch(url, method='POST', body=urllib.urlencode(post_args),
+                       callback=callback)
+        else:
+            http.fetch(url, callback=callback)
+
+
+    def _oauth_consumer_token(self):
+        return dict(
+            key=DOUBAN_CONSUMER_KEY,
+            secret=DOUBAN_CONSUMER_SECRET)
+
+    def _oauth_get_user(self, access_token, callback):
+        callback = self.async_callback(self._parse_user_response, callback)
+        douban_user_id = access_token['douban_user_id']
+        self._request(
+            '/people/%s'%douban_user_id,
+            access_token=access_token, callback=callback
+        )
+
+
+    def _parse_user_response(self, callback, xml):
+        if xml:
+            from BeautifulSoup import BeautifulStoneSoup
+            soup = BeautifulStoneSoup(xml)
+            user = dict(
+                name=soup.title.string,
+                uid=soup.find('db:uid').string
+            )
+        else:
+            user = None
+        callback(user)
+