跳至內容

Karrigell/計數器

來自 Wikibooks,面向開放世界創作的開放書籍

用來計算訪客訪問頁面的次數

# the counter is stored in a file called "counter"
try:
   c = int(open('counter').read())
except IOError:
   c = 0

if not hasattr(Session(),'page_counter'):
   c += 1
   f = open('counter','w')
   f.write(str(c))
   f.close()
   Session().page_counter = c

print Session().page_counter,'visits'

會話確保即使訪客重新整理頁面 100 次,此次訪問也只被計算一次。

當然,你可以將此指令碼包含在另一個指令碼中 (Include('counter.py'))。你甚至可以將檔名傳遞給 Include 函式,如果你需要為每個頁面管理不同的計數器。

華夏公益教科書