diff --git a/README.md b/README.md index 20f3123f..72fad64c 100644 --- a/README.md +++ b/README.md @@ -295,3 +295,20 @@ and code here might need to be updated if you are using Python 2.6+. * You'll likely want to set `LOGIN_URL` to `/login/` so that users are properly redirected to your Twitter login handler when you use `@login_required` in other parts of your Django app. * You can also set `AUTH_PROFILE_MODULE = 'mytwitterapp.Profile'` so that you can easily access the Twitter OAuth token/secret for that user using the `User.get_profile()` method in Django. + +# OAuth2 Example + +You might have thought from the name "oauth2" that this libary supported +the OAuth2 standard. You would have been wrong, except for the fine efforts +of https://github.com/dgouldin. Here is how you use it: + + import oauth2 + client = oauth2.Client2(CONSUMER_KEY, CONSUMER_SECRET, AUTHORIZATION_URL) + auth_url = client.authorization_url(redirect_uri = CALLBACK_URL) + print auth_url + # navigate to auth_url, to obtain code + token = client.access_token(code, CALLBACK_URL, endpoint='token')["access_token"] + print token + # use token to call secure APIs + (headers, content) = client.request(RESOURCE_URL, access_token=token) + ... diff --git a/oauth2/__init__.py b/oauth2/__init__.py index a3a4f687..9f4b45ba 100644 --- a/oauth2/__init__.py +++ b/oauth2/__init__.py @@ -29,6 +29,7 @@ import hmac import binascii import httplib2 +import json try: from urlparse import parse_qs, parse_qsl @@ -739,6 +740,13 @@ def _split_url_string(param_str): parameters[key] = urllib.unquote(val[0]) return parameters + @staticmethod + def _get_json(data): + """Turn json response into hash.""" + result = json.loads(data) + return result + + def authorization_url(self, redirect_uri=None, params=None, state=None, immediate=None, endpoint='authorize'): """Get the URL to redirect the user for client authorization @@ -800,7 +808,11 @@ def access_token(self, code, redirect_uri, params=None, secret_type=None, headers=headers) if not response.status == 200: raise Error(content) - response_args = Client2._split_url_string(content) + + if "json" in response['content-type']: + response_args = Client2._get_json(content) + else: + response_args = Client2._split_url_string(content) error = response_args.pop('error', None) if error is not None: