#----------------------- Header and Message -------------------------------
_quote = lambda s: '"' + s + '"' if s[0] != '"' != s[-1] else s
_unquote = lambda s: s[1:-1] if s[0] == '"' == s[-1] else s
这两个lambda函数用来加上和去除引号。 python支持用lambda定义单行函数,该函数对象又可以赋值给变量。
# various header types: standard (default), address, comma and unstructured
_address = ['contact', 'from', 'record-route', 'refer-to', 'referred-by', 'route', 'to']
_comma = ['authorization', 'proxy-authenticate', 'proxy-authorization', 'www-authenticate']
_unstructured = ['call-id', 'cseq', 'date', 'expires', 'max-forwards', 'organization', 'server', 'subject', 'timestamp', 'user-agent']
# short form of header names
_short = ['allow-events', 'u', 'call-id', 'i', 'contact', 'm', 'content-encoding', 'e', 'content-length', 'l', 'content-type', 'c', 'event', 'o', 'from', 'f', 'subject', 's', 'supported', 'k', 'to', 't', 'via', 'v']
# exception for canonicalization of header names
_exception = {'call-id':'Call-ID','cseq':'CSeq','www-authenticate':'WWW-Authenticate'}
#_canon = lambda s: '-'.join([x.capitalize() for x in s.split('-')]) if s.lower() not in ['cseq','call-id','www-authenticate'] else {'cseq':'CSeq','call-id':'Call-ID','www-authenticate':'WWW-Authenticate'}[s.lower()]
上面分别用列表和元组存储一些特殊的header
def _canon(s):
'''Return the canonical form of the header.
>>> print _canon('call-Id'), _canon('fRoM'), _canon('refer-to')
Call-ID From Refer-To
'''
s = s.lower()
return ((len(s)==1) and s in _short and _canon(_short[_short.index(s)-1])) \
or (s in _exception and _exception[s]) or '-'.join([x.capitalize() for x in s.split('-')])
上面代码定义了一个函数。作用是对字符串变化大小写,输出骆驼体格式的字符串。
比如"abc"会输出"Abc"。这里最后的return语句比较复杂。通过几个用例可以理解这段代码:
>>> _canon('u')
'Allow-Events'
((len(s)==1) and s in _short and _canon(_short[_short.index(s)-1]))
>>> _canon('call-id')
'Call-ID'
s in _exception and _exception[s]
>>> _canon('hello-world')
'Hello-World'
>>> _canon('abc')
'Abc'
>>> _canon("a-b-c")
'A-B-C'
'-'.join([x.capitalize() for x in s.split('-')])