RFC3261 python源码分析 2

#----------------------- 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('-')])


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值