寫Web應用(網站等)經常會用到Cookies。Sanic可以讀寫Cookies,並以key-value(鍵值對)的方式儲存。警告:因為Cookies很容易被客戶端修改,所以不能把登入資訊直接儲存到cookies裡面,而是經過加密後再放到cookies。後面我將寫一篇用於Sanic加密cookies的文章來介紹在Sanic中使用加密cookies的方法。
讀取cookies
使用者(客戶端)發來的資料都儲存在Request
物件裡面,其中也包含cookies。透過該物件的cookies
字典即可訪問使用者的cookies。
from sanic.response import text
@app.route("/cookie")
async def test(request):
test_cookie = request.cookies.get('test')
return text("Test cookie set to: {}".format(test_cookie))
寫入Cookies
返回響應時,可以吧cookies寫入到Response
物件。
from sanic.response import text
@app.route("/cookie")
async def test(request):
response = text("There's a cookie up in this response")
response.cookies['test'] = 'It worked!'
response.cookies['test']['domain'] = '.gotta-go-fast.com'
response.cookies['test']['httponly'] = True
return response
刪除cookies
可以在語義上或顯式刪除Cookie。
from sanic import Sanic
from sanic.response import text
app = Sanic()
@app.route("/cookie")
async def test(request):
response = text("Time to eat some cookies muahaha")
# 刪除一個不存在的cookie,就會把它的Max-age設定為0
del response.cookies['kill_me']
# 該cookie將在5秒內銷燬。
response.cookies['short_life'] = 'Glad to be here'
response.cookies['short_life']['max-age'] = 5
# 還是刪除一個不存在的cookies
del response.cookies['favorite_color']
# This cookie will remain unchanged
response.cookies['favorite_color'] = 'blue'
response.cookies['favorite_color'] = 'pink'
# 從cookies字典中移除`favorite_color`鍵
del response.cookies['favorite_color']
return response
if __name__ == '__main__':
app.run(host='127.0.0.1', port=8888)
透過curl檢視一下cookies的情況:
curl -i http://127.0.0.1:8888/cookie
可以看到如下輸出:
HTTP/1.1 200 OK
Connection: keep-alive
Keep-Alive: 5
Set-Cookie: kill_me=""; Path=/; Max-Age=0
Set-Cookie: short_life="Glad to be here"; Path=/; Max-Age=5
Content-Length: 32
Content-Type: text/plain; charset=utf-8
Time to eat some cookies muahaha
響應的cookies可以像字典那樣設定值,有效的鍵如下:
expire
(型別:datetime):cookie在客戶端的瀏覽器到期時間。path
(型別:string):cookie應用的URL子集。預設為/
。comment
(型別:string):註釋(metadata)。domain
(型別:string):指定cookie有效的域。 明確指定的域必須始終以點開頭。max-age
(型別:數字):cookie存活的秒數secure
(型別:boolean):指定cookie是否只透過HTTPS傳送。httponly
(型別:boolean):指定cookie是否能被Javascript讀取。
我的公眾號:猿人學 Python 上會分享更多心得體會,敬請關注。
***版權申明:若沒有特殊說明,文章皆是猿人學 yuanrenxue.com 原創,沒有猿人學授權,請勿以任何形式轉載。***