-1

I am using requests-oauthlib to authenticate with the ETrade API. It requires the authorization URL to have the following format:

https://us.etrade.com/e/t/etws/authorize?key={oauth_consumer_key}&token={oauth_token}

However, when I call authorization_url(), it uses oauth_token instead of token for that parameter. Currently I am using format() to format the URL myself, but now I have both token and oauth_token parameters. This works, but is completely inelegant. Is there some way to modify the behavior of authorization_url() to allow the URL format I require?

For completeness, here is my code:

oauth_session = requests_oauthlib.OAuth1Session(config.oauth_consumer_key, config.consumer_secret, callback_uri='oob')


def get_request_token():
    path = 'oauth/request_token'
    url = base_url + path
    return oauth_session.fetch_request_token(url)


def get_authorization_url(request_token):
    url_format = 'https://us.etrade.com/e/t/etws/authorize?key={oauth_consumer_key}&token={oauth_token}'
    url = url_format.format(oauth_consumer_key=config.oauth_consumer_key, oauth_token=request_token['oauth_token'])
    return oauth_session.authorization_url(url)

request_token = get_request_token()
print(get_authorization_url(request_token))
Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268

1 Answers1

1

The authorization_url() function is a convenience function which calls a generic function to add query parameters to a url (OAuthLib's common.add_params_to_uri() which in turn uses urlparse.urlunparse()). There is no way to get authorization_url() to leave out the oauth_token parameter.

The returned type is a str (in Python 3), so as long as you are certain that the url and tokens will only contain valid characters, you can obtain the same result by using a plain string format call as you have done in your function.

However if the additional oauth_token parameter causes no problems, I would suggest using the authorization_url() function for the extra safety provided.

Additionally, it is then unnecessary to do the extra str.format() call in your function - the authorization_url() takes kwargs which can be used to specify those parameters:

def get_authorization_url(request_token):
    url = 'https://us.etrade.com/e/t/etws/authorize'
    return oauth_session.authorization_url(url,
                                           key=config.oauth_consumer_key, 
                                           token=request_token['oauth_token'])
frenno
  • 11
  • 2
  • As far as I can tell, the extra `oauth_token` parameter doesn't cause any problems. What extra safety does `authorization_url()` provide? Does it URL-encode the tokens? Anything else? – Code-Apprentice Feb 10 '17 at 20:15