如何在 Python CGI 程式設計中設定 Cookie?


設定 Cookie

向瀏覽器傳送 Cookie 非常容易。這些 Cookie 會在 Content-type 欄位之前隨 HTTP 頭一同傳送。假設你要設定 UserID 和密碼作為 Cookie。設定 Cookie 的方法如下 −

#!/usr/bin/python
print "Set-Cookie:UserID = XYZ;\r\n"
print "Set-Cookie:Password = XYZ123;\r\n"
print "Set-Cookie:Expires = Tuesday, 31-Dec-2007 23:12:40 GMT;\r\n"
print "Set-Cookie:Domain = www.tutorialspoint.com;\r\n"
print "Set-Cookie:Path = /perl;\n"
print "Content-type:text/html\r\n\r\n"
...........Rest of the HTML Content....

透過此示例,你應該已經瞭解如何設定 Cookie。我們使用 Set-Cookie HTTP 頭來設定 Cookie。

還可以選擇設定 Expires、Domain 和 Path 等 Cookie 屬性。請注意,Cookie 需要在傳送魔術行 "Content-type:text/html\r\n\r\n.

更新於: 2019 年 8 月 30 日

634 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.