|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
- import requests
- from requests.auth import AuthBase
- class GithubAuth(AuthBase):
- def __init__(self,token):
- self.token = token
- def __call__(self,r):
- r.headers['Authorization'] = ' '.join(['token',self.token])
- return r
- def oauth_advanced():
- auth = GithubAuth('881319f3961ae9ddfgdfgdfgdfgwwercec7447') #这串token我经过处理了的
- response = requests.get('https://api.github.com/user/emails',auth=auth)
- print(response.text)
- oauth_advanced()
复制代码
这段代码是可以正常运行的
问题来了:
为什么在__call__上能成功调用参数r,但代码好像并没有传入过参数r
我用debug模式运行发现,r被传入了<PreparedRequest [GET]>,这是什么情况
D:\Python34\Lib\site-packages\requests\models.py
r = auth(self) # class PreparedRequest 把自身的实例传进去了
- def prepare_auth(self, auth, url=''):
- """Prepares the given HTTP auth data."""
- # If no Auth is explicitly provided, extract it from the URL first.
- if auth is None:
- url_auth = get_auth_from_url(self.url)
- auth = url_auth if any(url_auth) else None
- if auth:
- if isinstance(auth, tuple) and len(auth) == 2:
- # special-case basic HTTP auth
- auth = HTTPBasicAuth(*auth)
- # Allow auth to make its changes.
- r = auth(self) # class PreparedRequest 把自身的实例传进去了
- # Update self to reflect the auth changes.
- self.__dict__.update(r.__dict__)
- # Recompute Content-Length
- self.prepare_content_length(self.body)
复制代码
|
|