psf / requests

A simple, yet elegant, HTTP library.
https://requests.readthedocs.io/en/latest/
Apache License 2.0
52.13k stars 9.32k forks source link

AuthBase has unwieldy access to r.params #499

Closed jmoiron closed 12 years ago

jmoiron commented 12 years ago

Because _enc_params seems to already be built by the time auth is applied, and r.params is no longer a dictionary, authentication schemes that require signatures to be passed as a param (like LastFM's, possibly others) end up being kind of unwieldy. Here's some working LastFM auth code, for example:


from hashlib import md5
from requests.auth import AuthBase
from urllib import urlencode

key = "xxx"
secret = "xxx-secret"

class LastFMAuth(AuthBase):
    """Implement LastFM's annoying authentication."""
    def __init__(self, session_key):
        self.session_key = session_key

    def __call__(self, r):
        r.params.append(('sk', self.session_key))
        r.params.append(('api_key', key))
        encode = lambda x: unicode(x).encode("utf-8")
        signature = list(sorted(r.params))
        signature = "".join([encode(k) + encode(v) for k,v in signature]) + secret
        r.params.append(("api_sig", md5(signature).hexdigest()))
        r._enc_params = urlencode(r.params)
        return r

I think it would suffice to delay setting _enc_params until after auth is applied; even if such a thing is documented it still feels kind of strange.

kennethreitz commented 12 years ago

I believe this has changed recently.

jmoiron commented 12 years ago

request.params is indeed a dictionary in requests-0.13.1, which means the code in this ticket no longer works and the _enc_params = urlencode(...) step is no longer necessary for auth using params.

gpg90 commented 11 years ago

@jmoiron @kennethreitz I'm sorry, but how can it be currently done? Building API client for another service that uses signature-based authentication and when I'm trying to add parameters by editing r.params, I receive: AttributeError: 'PreparedRequest' object has no attribute 'params'

sigmavirus24 commented 11 years ago

@pitsevich the API has changed in the most recent releases of requests. As of 1.x you have no access to the params attribute. If you want to modify the params you'll have to parse the url and unquote the param string, add your params, re-quote it and then unparse the url.

gpg90 commented 11 years ago

@sigmavirus24 thanks, this worked!

sigmavirus24 commented 11 years ago

@pitsevich glad to help.