繁体   English   中英

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

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

我在github上的主kennethreitz / requests中深入研究了request / 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对象只是一个字典数据结构。

在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'])

你好标题

对Python字典数据结构网页了解详情。

编辑:

2秒浏览您链接到的源文件将显示以下行

from .utils import parse_dict_header, to_native_string

我认为不用研究它,可以肯定地说header属性只是一个字典parse_dict_header

编辑2:回答有关r.headers具体问题。

__call__方法是当像调用一个函数那样__call__ HTTPBasicAuth对象时,我可以通过代码进行跟踪,并查看此处Request对象的prepare_auth方法中的第487行发生的情况。

r = auth(self)

其中self是Request对象实例。 Request具有自己的标头属性,该属性在第225行的__init__中设置。

self.headers = headers

就是在models.py中定义的这个Request对象,它是传递给HTTPBasicAuth类的__call__方法的参数r

如果使用Python Visual Studio Calls之类的代码,则可以运行此代码,在感兴趣的行上中断,在这种情况下,使用r.headers,然后查看Backstack并探索作用域中的对象。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM