r.headers['Authorization'] 在 python2.7 class 的 __call__ 函数中

r.headers['Authorization'] in python2.7 class's __call__ function

我正在 github 上 kennethreitz/requests 的 master requests/requests/auth.py 文件中挖掘一点。

https://github.com/kennethreitz/requests/blob/master/requests/auth.py

我看到这段代码,

class HTTPBasicAuth(AuthBase):
"""Attaches HTTP Basic Authentication to the given Request object."""
def __init__(self, username, password):
    self.username = username
    self.password = password

def __call__(self, r):
    r.headers['Authorization'] = _basic_auth_str(self.username, self.password)
    return r

我只是不明白他怎么能想出以前没有定义过的 r.headerp['Authorisation ']。我错过了什么吗?

非常感谢有人回答这个问题:)

我假设 r.headers object 只是一个字典数据结构。

在 Python 中,您可以获取字典并分配任何属性,无论是否存在,如果它不存在,则会创建它。

如果你启动 python shell

就可以看到这个
#Create a new empty dictionary, no attributes
>>> obj = {}
#Assign the string "hello header" to the "headers" attribute
>>> obj['headers'] = "hello header"
# Print it
>>> print(obj['headers'])

hello header

请参阅 python 字典数据结构上的 this 页面以了解更多信息。

编辑:

看一眼您链接到的源文件会显示该行

from .utils import parse_dict_header, to_native_string

我认为不看它就可以安全地说 header 属性只是一个字典 - parse_dict_header.

编辑 2: 回答关于 r.headers 来自哪里的更具体的问题。

__call__ 方法是当 HTTPBasicAuth object 像一个函数一样被调用时,我可以跟踪代码并在第 487 行看到 here 发生的情况,这是在 Request object.

prepare_auth 方法中
r = auth(self)

其中 self 是 Request object 实例。 Request 在第 225 行的 __init__ 中设置了自身的 headers 属性。

self.headers = headers

就是models.py中定义的这个Request object是传递给HTTPBasicAuth__call__方法的参数r class.

如果您使用 Python Visual Studio 之类的调用,您可以 运行 此代码,在您感兴趣的行上中断,在本例中 r.headers被使用,并查看此时的后台堆栈并探索范围内的 objects。