webpy原始碼閱讀 1 初見整體

2021-06-27 19:28:19 字數 2660 閱讀 6535

最近閒來無事,準備看看web.py的原始碼,一開始直接看現在的原始碼,發現比較吃力,後來想起從github上clone下來後checkout到2023年的那個第乙個版本開始,700多次commit,準備一次次的看,記錄下自己的閱讀所得

最開始版本的web.py就乙個web.py檔案,一共1000行多一點,其中還有300行是模板,不得不佩服aaron swartz,不愧是世界著名的黑客

我在閱讀後,把其中例如資料庫操作這類的模組去除,只留下了wsgi的執行過程,下面慢慢放上

首先web.py裡面的乙個main**塊,

if __name__ == "__main__":

urls = ('/web.py', 'source')

class source:

def get(self):

header('content-type', 'text/python')

print open(__file__).read()

run(urls)

自定義乙個url與handle的對應關係序列,再啟動伺服器,等待處理

大致分析一下結構

大概流程就是以上

其中見到幾個比較有意思的**

class memoize:

def __init__(self, func):

self.func = func

self.cache = {}

def __call__(self, *args, **kwargs):

key = (args, tuple(kwargs.items()))

if key not in self.cache:

self.cache[key] = self.func(*args, **kwargs)

return self.cache[key]

這個函式可以為函式提供返回值的快取

import re

re_compile = memoize(re.compile)

r = re_compile('\d+')r = re_compile('\d+')

r = re_compile('\w+')
結果為 

('not cache', (('\\d+',), ()))

('not cache', (('\\w+',), ()))

[finished in 0.0s]

很明顯把正則編譯的結果快取了,這樣提高效率,還有提公升**優美度很好感覺

一開始有個地方看的不太明白

class source:

def get(self):

print input()

header('content-type', 'text/python')

print open(__file__).read()

為何是print 我們通常用到的webpy都是返回值,而且並沒有控制台輸出

後來發現下面的**

class _outputter:

def write(self, x):

if hasattr(ctx, 'output'): output(x)

else: _oldstdout.write(x)

if not '_oldstdout' in globals():

_oldstdout = sys.stdout

sys.stdout = _outputter()

context又是什麼?

class threadeddict:

def __init__(self, d): self.__dict__['_threadeddict__d'] = d

def __getattr__(self, a): return getattr(self.__d[currentthread()], a)

def __getitem__(self, i): return self.__d[currentthread()][i]

def __setattr__(self, a, v): return setattr(self.__d[currentthread()], a, v)

def __setitem__(self, i, v): self.__d[currentthread()][i] = v_context =

ctx = context = threadeddict(_context)

我們看到threadeddict()是乙個按執行緒索引儲存資料的物件,也就是我們平時用到的web.ctx物件,原來是這麼是實現的! 

當前請求的所有資訊,還有響應的所有資訊都在裡面,包括響應body  context.output

但為何要用print實現呢,return不是也一樣嗎,還更加直觀。

期待後面的commit帶來新的收穫!

_context = 

ctx = context = threadeddict(_context)

webpy原始碼閱讀 開篇

我剛開始學習webpy的時候根據官網文件能完成大部分功能,但用著用著還是感覺有些不太爽感覺自己使用不靈活,有些功能想實現不知道該怎樣入手,而現在網上關於深入使用webpy的開發資料也很少。所以決定還是自己來看看原始碼吧,很慶幸webpy原始碼不多 應該是很少 看兩個小時就能理清楚了。1 首先看看we...

一 Spring原始碼閱讀 整體概況

一 spring能幹啥 1.進行物件的管理,物件的建立和銷毀,不用使用new來進行物件建立了 準備寫第二條的,發現spring核心內容就是物件管理,那為什麼必須是spring呢?2.如果僅僅是物件管理,那其實很容易實現,關鍵是其還有豐富的生態圈,基於spring會有很多的元件,這些元件可以在spri...

Amass專案原始碼閱讀 整體架構

本文寫於 amass v3.11.2,可能後續有過更多變更,但是應該整體邏輯不會有十分大的變動了 首先鋪墊下在 amass 用到的兩大設計模式 發布訂閱模式 流水線 pipeline 模式 在 4432dbd 該提交之前,即 v3.11.0 版本前,其實並沒有流水線模式,並且採用的是 golang ...