Skip to content

Py3k compatibility #142

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 27 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
6f58f7f
Document / test supported python versions.
tseaver May 28, 2013
55fb8f6
Coverage for o._version.
tseaver May 28, 2013
16e45f8
Python 2.5 is still supported.
tseaver May 28, 2013
cd1a95a
Restore 100% coverage.
tseaver May 28, 2013
457d64b
Py3k: print statements.
tseaver May 28, 2013
e058ec9
Drop Python 2.5 suport.
tseaver May 28, 2013
463cb09
Py3: use 'except ... as' syntax.
tseaver May 29, 2013
f81d183
Tidy imports.
tseaver May 29, 2013
7d72ac1
PEP8: Wrap 80+ column lines.
tseaver May 29, 2013
e7d1be0
Unshadow 'test_to_string'.
tseaver May 29, 2013
9fc3e66
Normalize
tseaver May 29, 2013
f8c0ece
Normalize away unicode literals.
tseaver May 29, 2013
517dbd8
Py3: compatible imports.
tseaver May 29, 2013
69cb2b9
Don't use non-ASCII bytes literals.
tseaver May 29, 2013
17880b6
Restore coverage.
tseaver May 29, 2013
3d5d52f
Add a 'b()' utility for forcing encoding to bytes.
tseaver Jun 4, 2013
da9145c
Moar Py3k compat.
tseaver Jun 4, 2013
bb7568f
Restore correct split of urlquoted UTF-8 query strings under Python2.
tseaver Jun 5, 2013
4000723
Run tests under tox on Python 3.2.
tseaver Jun 5, 2013
63db42c
Accomodate hash randomization.
tseaver Jun 5, 2013
1d37881
Avoid shadowing imported 'b' function.
tseaver Jun 5, 2013
1f7134b
Accomodate hash randomization moar.
tseaver Jun 5, 2013
f26d9c0
Run tests under tox on Python 3.3.
tseaver Jun 5, 2013
fb2b824
Silence Py3k unittest nannyisms.
tseaver Jun 5, 2013
b042c22
Note support for Python 3.2 and 3.3.
tseaver Jun 5, 2013
05e2ffb
Remove spurious 'str()' conversion.
tseaver Jun 5, 2013
0406587
Ensure we parse qs as test in Token.from_string.
tseaver Jun 5, 2013
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
*.py?
*.egg-info
*.swp
.coverage
coverage.xml
nosetests.xml
.tox
4 changes: 2 additions & 2 deletions example/appengine_oauth.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ def is_valid(self):
request = self.get_oauth_request()
client = self.get_client(request)
params = self._server.verify_request(request, client, None)
except Exception, e:
except Exception as e:
raise e

return client
Expand All @@ -95,7 +95,7 @@ class SampleHandler(OAuthHandler):
def get(self):
try:
client = self.is_valid()
except Exception, e:
except Exception as e:
self.error(500)
self.response.out.write(e)

Expand Down
96 changes: 56 additions & 40 deletions example/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,125 +41,141 @@
CALLBACK_URL = 'http://printer.example.com/request_token_ready'
RESOURCE_URL = 'http://photos.example.net/photos'

# key and secret granted by the service provider for this consumer application - same as the MockOAuthDataStore
# key and secret granted by the service provider for this consumer
# application - same as the MockOAuthDataStore
CONSUMER_KEY = 'key'
CONSUMER_SECRET = 'secret'

# example client using httplib with headers
class SimpleOAuthClient(oauth.OAuthClient):

def __init__(self, server, port=httplib.HTTP_PORT, request_token_url='', access_token_url='', authorization_url=''):
def __init__(self, server, port=httplib.HTTP_PORT, request_token_url='',
access_token_url='', authorization_url=''):
self.server = server
self.port = port
self.request_token_url = request_token_url
self.access_token_url = access_token_url
self.authorization_url = authorization_url
self.connection = httplib.HTTPConnection("%s:%d" % (self.server, self.port))
self.connection = httplib.HTTPConnection(
"%s:%d" % (self.server, self.port))

def fetch_request_token(self, oauth_request):
# via headers
# -> OAuthToken
self.connection.request(oauth_request.http_method, self.request_token_url, headers=oauth_request.to_header())
self.connection.request(oauth_request.http_method,
self.request_token_url, headers=oauth_request.to_header())
response = self.connection.getresponse()
return oauth.OAuthToken.from_string(response.read())

def fetch_access_token(self, oauth_request):
# via headers
# -> OAuthToken
self.connection.request(oauth_request.http_method, self.access_token_url, headers=oauth_request.to_header())
self.connection.request(oauth_request.http_method,
self.access_token_url, headers=oauth_request.to_header())
response = self.connection.getresponse()
return oauth.OAuthToken.from_string(response.read())

def authorize_token(self, oauth_request):
# via url
# -> typically just some okay response
self.connection.request(oauth_request.http_method, oauth_request.to_url())
self.connection.request(oauth_request.http_method,
oauth_request.to_url())
response = self.connection.getresponse()
return response.read()

def access_resource(self, oauth_request):
# via post body
# -> some protected resources
headers = {'Content-Type' :'application/x-www-form-urlencoded'}
self.connection.request('POST', RESOURCE_URL, body=oauth_request.to_postdata(), headers=headers)
self.connection.request('POST', RESOURCE_URL,
body=oauth_request.to_postdata(),
headers=headers)
response = self.connection.getresponse()
return response.read()

def run_example():

# setup
print '** OAuth Python Library Example **'
client = SimpleOAuthClient(SERVER, PORT, REQUEST_TOKEN_URL, ACCESS_TOKEN_URL, AUTHORIZATION_URL)
print('** OAuth Python Library Example **')
client = SimpleOAuthClient(SERVER, PORT, REQUEST_TOKEN_URL,
ACCESS_TOKEN_URL, AUTHORIZATION_URL)
consumer = oauth.OAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET)
signature_method_plaintext = oauth.OAuthSignatureMethod_PLAINTEXT()
signature_method_hmac_sha1 = oauth.OAuthSignatureMethod_HMAC_SHA1()
pause()

# get request token
print '* Obtain a request token ...'
print('* Obtain a request token ...')
pause()
oauth_request = oauth.OAuthRequest.from_consumer_and_token(consumer, callback=CALLBACK_URL, http_url=client.request_token_url)
oauth_request = oauth.OAuthRequest.from_consumer_and_token(
consumer, callback=CALLBACK_URL, http_url=client.request_token_url)
oauth_request.sign_request(signature_method_plaintext, consumer, None)
print 'REQUEST (via headers)'
print 'parameters: %s' % str(oauth_request.parameters)
print('REQUEST (via headers)')
print('parameters: %s' % str(oauth_request.parameters))
pause()
token = client.fetch_request_token(oauth_request)
print 'GOT'
print 'key: %s' % str(token.key)
print 'secret: %s' % str(token.secret)
print 'callback confirmed? %s' % str(token.callback_confirmed)
print('GOT')
print('key: %s' % str(token.key))
print('secret: %s' % str(token.secret))
print('callback confirmed? %s' % str(token.callback_confirmed))
pause()

print '* Authorize the request token ...'
print('* Authorize the request token ...')
pause()
oauth_request = oauth.OAuthRequest.from_token_and_callback(token=token, http_url=client.authorization_url)
print 'REQUEST (via url query string)'
print 'parameters: %s' % str(oauth_request.parameters)
oauth_request = oauth.OAuthRequest.from_token_and_callback(
token=token, http_url=client.authorization_url)
print('REQUEST (via url query string)')
print('parameters: %s' % str(oauth_request.parameters))
pause()
# this will actually occur only on some callback
response = client.authorize_token(oauth_request)
print 'GOT'
print response
print('GOT')
print(response)
# sad way to get the verifier
import urlparse, cgi
query = urlparse.urlparse(response)[4]
params = cgi.parse_qs(query, keep_blank_values=False)
verifier = params['oauth_verifier'][0]
print 'verifier: %s' % verifier
print('verifier: %s' % verifier)
pause()

# get access token
print '* Obtain an access token ...'
print('* Obtain an access token ...')
pause()
oauth_request = oauth.OAuthRequest.from_consumer_and_token(consumer, token=token, verifier=verifier, http_url=client.access_token_url)
oauth_request = oauth.OAuthRequest.from_consumer_and_token(
consumer, token=token, verifier=verifier,
http_url=client.access_token_url)
oauth_request.sign_request(signature_method_plaintext, consumer, token)
print 'REQUEST (via headers)'
print 'parameters: %s' % str(oauth_request.parameters)
print('REQUEST (via headers)')
print('parameters: %s' % str(oauth_request.parameters))
pause()
token = client.fetch_access_token(oauth_request)
print 'GOT'
print 'key: %s' % str(token.key)
print 'secret: %s' % str(token.secret)
print('GOT')
print('key: %s' % str(token.key))
print('secret: %s' % str(token.secret))
pause()

# access some protected resources
print '* Access protected resources ...'
print('* Access protected resources ...')
pause()
parameters = {'file': 'vacation.jpg', 'size': 'original'} # resource specific params
oauth_request = oauth.OAuthRequest.from_consumer_and_token(consumer, token=token, http_method='POST', http_url=RESOURCE_URL, parameters=parameters)
parameters = {'file': 'vacation.jpg',
'size': 'original'} # resource specific params
oauth_request = oauth.OAuthRequest.from_consumer_and_token(consumer,
token=token, http_method='POST', http_url=RESOURCE_URL,
parameters=parameters)
oauth_request.sign_request(signature_method_hmac_sha1, consumer, token)
print 'REQUEST (via post body)'
print 'parameters: %s' % str(oauth_request.parameters)
print('REQUEST (via post body)')
print('parameters: %s' % str(oauth_request.parameters))
pause()
params = client.access_resource(oauth_request)
print 'GOT'
print 'non-oauth parameters: %s' % params
print('GOT')
print('non-oauth parameters: %s' % params)
pause()

def pause():
print ''
print('')
time.sleep(1)

if __name__ == '__main__':
run_example()
print 'Done.'
print('Done.')
34 changes: 22 additions & 12 deletions example/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,11 @@ def lookup_token(self, token_type, token):
return None

def lookup_nonce(self, oauth_consumer, oauth_token, nonce):
if oauth_token and oauth_consumer.key == self.consumer.key and (oauth_token.key == self.request_token.key or oauth_token.key == self.access_token.key) and nonce == self.nonce:
if (oauth_token and
oauth_consumer.key == self.consumer.key and
(oauth_token.key == self.request_token.key or
oauth_token.key == self.access_token.key) and
nonce == self.nonce):
return self.nonce
return None

Expand All @@ -74,7 +78,9 @@ def fetch_request_token(self, oauth_consumer, oauth_callback):
return None

def fetch_access_token(self, oauth_consumer, oauth_token, oauth_verifier):
if oauth_consumer.key == self.consumer.key and oauth_token.key == self.request_token.key and oauth_verifier == self.verifier:
if (oauth_consumer.key == self.consumer.key and
oauth_token.key == self.request_token.key and
oauth_verifier == self.verifier):
# want to check here if token is authorized
# for mock store, we assume it is
return self.access_token
Expand All @@ -91,8 +97,10 @@ class RequestHandler(BaseHTTPRequestHandler):

def __init__(self, *args, **kwargs):
self.oauth_server = oauth.OAuthServer(MockOAuthDataStore())
self.oauth_server.add_signature_method(oauth.OAuthSignatureMethod_PLAINTEXT())
self.oauth_server.add_signature_method(oauth.OAuthSignatureMethod_HMAC_SHA1())
self.oauth_server.add_signature_method(
oauth.OAuthSignatureMethod_PLAINTEXT())
self.oauth_server.add_signature_method(
oauth.OAuthSignatureMethod_HMAC_SHA1())
BaseHTTPRequestHandler.__init__(self, *args, **kwargs)

# example way to send an oauth error
Expand All @@ -119,7 +127,8 @@ def do_GET(self):
pass

# construct the oauth request from the request parameters
oauth_request = oauth.OAuthRequest.from_request(self.command, self.path, headers=self.headers, query_string=postdata)
oauth_request = oauth.OAuthRequest.from_request(self.command,
self.path, headers=self.headers, query_string=postdata)

# request token
if self.path.startswith(REQUEST_TOKEN_URL):
Expand All @@ -131,7 +140,7 @@ def do_GET(self):
self.end_headers()
# return the token
self.wfile.write(token.to_string())
except oauth.OAuthError, err:
except oauth.OAuthError as err:
self.send_oauth_error(err)
return

Expand All @@ -148,7 +157,7 @@ def do_GET(self):
self.end_headers()
# return the callback url (to show server has it)
self.wfile.write(token.get_callback_url())
except oauth.OAuthError, err:
except oauth.OAuthError as err:
self.send_oauth_error(err)
return

Expand All @@ -162,21 +171,22 @@ def do_GET(self):
self.end_headers()
# return the token
self.wfile.write(token.to_string())
except oauth.OAuthError, err:
except oauth.OAuthError as err:
self.send_oauth_error(err)
return

# protected resources
if self.path.startswith(RESOURCE_URL):
try:
# verify the request has been oauth authorized
consumer, token, params = self.oauth_server.verify_request(oauth_request)
consumer, token, params = self.oauth_server.verify_request(
oauth_request)
# send okay response
self.send_response(200, 'OK')
self.end_headers()
# return the extra parameters - just for something to return
self.wfile.write(str(params))
except oauth.OAuthError, err:
except oauth.OAuthError as err:
self.send_oauth_error(err)
return

Expand All @@ -186,10 +196,10 @@ def do_POST(self):
def main():
try:
server = HTTPServer(('', 8080), RequestHandler)
print 'Test server running...'
print('Test server running...')
server.serve_forever()
except KeyboardInterrupt:
server.socket.close()

if __name__ == '__main__':
main()
main()
Loading