Illustrations by Artur Sadlos
作者:愛看七龍珠
博客:zhihu.com/c_1046065830684614656
這篇文章我們來聊聊Cookie和Session,網(wǎng)上有很多關于這兩個知識點的描述,可惜的是大部分都沒有示例代碼,因此本文的重點在于示例代碼。
環(huán)境
Python3.6.0
Bottle0.12.15
安裝bottle
pip install bottle
Cookie
HTTP是一種無狀態(tài)協(xié)議,簡單來說就是如果A第一次訪問了B服務器,那么A第二次訪問B服務器時,B服務器并不知道這次訪問是否還是來自A。B服務器只負責接收網(wǎng)絡信息包,傳遞網(wǎng)絡信息包。這樣速度很快,但是很不方便,B服務器不會記錄A的數(shù)據(jù)。
為此,人們發(fā)明了Cookie,Cookie利用了HTTP中的Headers字段
HTTP/1.1 200 OK
Date: Mon, 23 May 2005 22:38:34 GMT
Content-Type: text/html; charset=UTF-8
Content-Length: 138
Last-Modified: Wed, 08 Jan 2003 23:11:55 GMT
Server: Apache/1.3.3.7 (Unix) (Red-Hat/Linux)
ETag: '3f80f-1b6-3e1cb03b'
Accept-Ranges: bytes
Connection: close
cookie: _zap=8aa393b0-cc62-4c6a
現(xiàn)在A每次訪問時都帶上cookie,B服務器就可以獲得A的cookie,這樣B服務器就能記住一些東西
假如說我們現(xiàn)在要統(tǒng)計A一共訪問了幾次B服務器,我們可以編寫以下代碼
cookie.py
from bottle import route, run, response, request
@route('/hello')
def hello():
count = request.get_cookie('visited')
if count:
increment = int(count) + 1
response.set_cookie('visited', str(increment))
return str(increment)
else:
response.set_cookie('visited', '0')
return 'Hello, World'
run(host='localhost', port=8080, debug=True)
需要說明一點:在整個傳輸過程中傳輸?shù)氖亲址?,如果傳進去一個整數(shù),那么會報錯,因此數(shù)字必須轉(zhuǎn)換為字符
執(zhí)行 python cookie.py
Session
Session一般用于登錄功能,我們利用Cookie實現(xiàn)了有狀態(tài)的傳輸,那么完全可以設置一個id,每次訪問的時候都會帶上這個id,這樣B服務器就能夠識別是誰訪問了
一般來說,拿到id之后會存儲在數(shù)據(jù)庫里面,為了方便起見,在這里只存儲到字典里面
session.py
from bottle import route, run, response, request, redirect
login_user = {} #用來存儲登錄狀態(tài)的字典
@route('/login')
def login():
key = hash('test password')
login_user[key] = 'test password'
response.set_cookie('login', str(key))
return 'login successfuly!'
@route('/logout')
def logout():
key = request.get_cookie('login')
login_user.pop(int(key), None)
return 'logout successfuly!'
@route('/logintest')
def logintest():
key = request.get_cookie('login')
if key is not None and int(key) in login_user:
return 'login test successfuly!'
else :
return redirect('/beforelogin')
@route('/beforelogin')
def beforelogin():
return 'please login!'
run(host='localhost', port=8080, debug=True)
執(zhí)行
python session.py