如何使用 Python CGI 程式設計設定 cookie?


設定 Cookie

向瀏覽器傳送 Cookie 非常容易。在將這些 Cookie 傳送到瀏覽器之前,它們會與 HTTP 頭一起傳送到 Content-Type 欄位之前。假設你想將 UserID 和 Password 作為 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 是在傳送 magic line "Content-type:text/html\r\n\r\n." 之前設定的。

更新於:2019 年 8 月 30 日

631 次瀏覽

開啟您的 職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.