天天看點

RFC3261 python源碼分析 1

在學習一門語言的基本文法後下一步做什麼呢?我覺得就是應該閱讀真實項目的代碼,這樣才能從玩具型的小程式轉向真實世界的系統代碼。進而在真實世界中使用它。

最近學習了python,想進一步看看實際項目中代碼。看到有個開源項目是用python來實作Peer-to-Peer SIP,這和我的工作正好相關。是以打算先對其源碼做一次詳盡的剖析。

大概每次剖析20行代碼。

首先是RFC3261協定實作。在RFC3261.py中。

# Copyright (c) 2007, Kundan Singh. All rights reserved. See LICENSING for details.
# @implements RFC3261 (SIP)
# @implements RFC3581 (rport)

'''
The session initiation protocol (SIP) as per RFC 3261.
In my code there is no performance optimization, if it hurts the style and
compactness of the code.
'''
           

這裡#開始的是注釋行。說明了該源碼的版權資訊和實作了哪些協定。

三引号這一段在python中被稱為"block string",可以用來表達多行的字元串。

import re, socket, traceback, uuid
from kutil import getlocaladdr
from rfc2396import isIPv4, isMulticast, isLocal, isPrivate, URI,Address
from rfc2617import createAuthorization
from socketimport gethostbyname# TODO: should replace with getifaddr, SRV, NAPTR or similar
           

上面幾行代碼是關于python的子產品機制。在python中每個檔案就是一個子產品。要引用一個子產品内的名字,可以用下面幾種格式:

import [module]

from [module] import [name]

from [module] import *

後面兩種方式會把子產品的特定或是以名字拷貝到目前的範圍。這樣可以直接使用引用的名字。而第一種方式則需要用module.name格式引用。

_debug=False
           

子產品變量,表示是否是debug模式。這裡的命名使用_表示子產品變量,符合google python style:

http://google-styleguide.googlecode.com/svn/trunk/pyguide.html#Naming