Li Huan avatar Li Huan committed d5c584a

RenRen API.

Comments (0)

Files changed (3)

+settings.py
+.renren_access_token
+.*\.pyc
+#!/usr/bin/env python
+# -*- coding: UTF-8 -*-
+
+import logging
+import urllib
+import BaseHTTPServer
+from urlparse import urlparse, parse_qs
+
+from renren import RENREN_AUTHORIZATION_URI, RENREN_ACCESS_TOKEN_URI
+from renren import RenRenAPI
+
+from settings import RENREN_APP_API_KEY, RENREN_APP_SECRET_KEY
+
+# Find a JSON parser
+try:
+    import json
+    _parse_json = lambda s: json.loads(s)
+except ImportError:
+    import simplejson
+    _parse_json = lambda s: simplejson.loads(s)
+
+ACCESS_TOKEN_FILE = '.renren_access_token'
+
+SERVER_PORT = 8099
+
+class _RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
+
+    def do_GET(self):
+        self.send_response(200)
+        self.send_header("Content-type", "text/html")
+        self.end_headers()
+
+        params = parse_qs(urlparse(self.path).query)
+        code = params.get('code', [None])[0]
+        print "code: " + code
+        if code:
+            args = {'client_id':RENREN_APP_API_KEY, 'redirect_uri':'http://127.0.0.1:%s/' % SERVER_PORT}
+            args["client_secret"] = RENREN_APP_SECRET_KEY
+            args["code"] = code
+            args["grant_type"] = "authorization_code"
+            print RENREN_ACCESS_TOKEN_URI + "?" + urllib.urlencode(args)
+            response = urllib.urlopen(RENREN_ACCESS_TOKEN_URI + "?" + urllib.urlencode(args)).read()
+            print response
+            access_token = _parse_json(response)["access_token"]
+            print "obtained access_token is: " + access_token
+
+            open(ACCESS_TOKEN_FILE,'w').write(json.dumps(response))
+
+            params = {"method": "users.getInfo", "fields": "name,tinyurl"}
+            api = RenRenAPI(access_token, RENREN_APP_API_KEY, RENREN_APP_SECRET_KEY)
+            response = api.request(params)
+
+            if type(response) is list:
+                response = response[0]
+
+            user_id = response["uid"]
+            name = response["name"]
+            avatar = response["tinyurl"]
+
+            print user_id, name, avatar
+
+            self.wfile.write("You have successfully logged in to renren with console. "
+                                     "You can close this window now.")
+        else:
+            self.wfile.write('<html><head>'
+                             '<script>location = "?"+location.hash.slice(1);</script>'
+                             '</head></html>')
+
+
+if __name__ == '__main__':
+    args = {'client_id':RENREN_APP_API_KEY, 'redirect_uri':'http://127.0.0.1:%s/' % SERVER_PORT}
+    args["response_type"] = "code"
+    args["scope"] = "publish_feed email status_update"
+    args["display"] = "touch"  #mobile -> wap, smartphone -> touch
+    print RENREN_AUTHORIZATION_URI + "?" + urllib.urlencode(args)
+
+    import webbrowser
+    webbrowser.open(RENREN_AUTHORIZATION_URI + "?" + urllib.urlencode(args))
+
+    httpd = BaseHTTPServer.HTTPServer(('127.0.0.1', SERVER_PORT), _RequestHandler)
+    httpd.handle_request()
+
+
+#!/usr/bin/env python
+# -*- coding: UTF-8 -*-
+
+import logging
+import hashlib
+import time
+import urllib
+
+# Find a JSON parser
+try:
+    import json
+    _parse_json = lambda s: json.loads(s)
+except ImportError:
+    import simplejson
+    _parse_json = lambda s: simplejson.loads(s)
+
+RENREN_AUTHORIZATION_URI = "http://graph.renren.com/oauth/authorize"
+RENREN_ACCESS_TOKEN_URI = "http://graph.renren.com/oauth/token"
+RENREN_API_SERVER = "http://api.renren.com/restserver.do"
+
+class RenRenAPI(object):
+
+    def __init__(self, access_token=None, api_key=None, secret_key=None):
+        self.access_token = access_token
+        self.api_key = api_key
+        self.secret_key = secret_key
+
+    def request(self, params=None):
+        """
+        Fetches the given method's response returning from RenRen API.
+
+        Send a POST request to the given method with the given params.
+        """
+        params["access_token"] = self.access_token
+        params["call_id"] = str(int(time.time() * 1000))
+        params["format"] = "json"
+        params["v"] = '1.0'
+        sig = self.hash_params(params);
+        params["sig"] = sig
+
+        post_data = None if params is None else urllib.urlencode(params)
+
+        file = urllib.urlopen(RENREN_API_SERVER, post_data)
+
+        try:
+            response = _parse_json(file.read())
+        finally:
+            file.close()
+
+        if type(response) is not list and response["error_code"]:
+            logging.info(response["error_msg"])
+            raise RenRenAPIError(response["error_code"], response["error_msg"])
+
+        return response
+
+    def hash_params(self, params = None):
+        hasher = hashlib.md5("".join(["%s=%s" % (self.unicode_encode(x), self.unicode_encode(params[x])) for x in sorted(params.keys())]))
+        hasher.update(self.secret_key)
+        return hasher.hexdigest()
+
+    def unicode_encode(self, str):
+        """
+        Detect if a string is unicode and encode as utf-8 if necessary
+        """
+        return isinstance(str, unicode) and str.encode('utf-8') or str
+
+class RenRenAPIError(Exception):
+    def __init__(self, code, message):
+        Exception.__init__(self, message)
+        self.code = code
+
+
+
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.