Skip to content
This repository was archived by the owner on Aug 7, 2024. It is now read-only.

Commit 8c5a036

Browse files
authored
Merge pull request #508 from bear/fix/issue494
Fix issue #494 for py3 compat w/ app only auth
2 parents 70dbada + 3ee3c5a commit 8c5a036

File tree

2 files changed

+16
-7
lines changed

2 files changed

+16
-7
lines changed

tests/test_api_30.py

+11
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,17 @@ def testApiRaisesAuthErrors(self):
8888
api._Api__auth = None
8989
self.assertRaises(twitter.TwitterError, lambda: api.GetFollowers())
9090

91+
@responses.activate
92+
def testAppOnlyAuth(self):
93+
responses.add(method=POST,
94+
url='https://api.twitter.com/oauth2/token',
95+
body='{"token_type":"bearer","access_token":"testing"}')
96+
api = twitter.Api(
97+
consumer_key='test',
98+
consumer_secret='test',
99+
application_only_auth=True)
100+
self.assertEqual(api._bearer_token['access_token'], "testing")
101+
91102
@responses.activate
92103
def testGetHelpConfiguration(self):
93104
with open('testdata/get_help_configuration.json') as f:

twitter/api.py

+5-7
Original file line numberDiff line numberDiff line change
@@ -35,13 +35,13 @@
3535

3636
try:
3737
# python 3
38-
from urllib.parse import urlparse, urlunparse, urlencode
38+
from urllib.parse import urlparse, urlunparse, urlencode, quote_plus
3939
from urllib.request import urlopen
4040
from urllib.request import __version__ as urllib_version
4141
except ImportError:
4242
from urlparse import urlparse, urlunparse
4343
from urllib2 import urlopen
44-
from urllib import urlencode
44+
from urllib import urlencode, quote_plus
4545
from urllib import __version__ as urllib_version
4646

4747
from twitter import (
@@ -288,17 +288,15 @@ def GetAppOnlyAuthToken(self, consumer_key, consumer_secret):
288288
"""
289289
Generate a Bearer Token from consumer_key and consumer_secret
290290
"""
291-
from urllib import quote_plus
292-
import base64
293-
294291
key = quote_plus(consumer_key)
295292
secret = quote_plus(consumer_secret)
296-
bearer_token = base64.b64encode('{}:{}'.format(key, secret))
293+
bearer_token = base64.b64encode('{}:{}'.format(key, secret).encode('utf8'))
297294

298295
post_headers = {
299-
'Authorization': 'Basic ' + bearer_token,
296+
'Authorization': 'Basic {0}'.format(bearer_token.decode('utf8')),
300297
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
301298
}
299+
302300
res = requests.post(url='https://api.twitter.com/oauth2/token',
303301
data={'grant_type': 'client_credentials'},
304302
headers=post_headers)

0 commit comments

Comments
 (0)