在 Python 中設定 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。

可以設定 Cookie 的屬性,如到期時間、域名和路徑,但這是可選的。需要注意的是,Cookie是在傳送特殊字串之前設定的:"Content-type:text/html\r\n\r\n.

更新於: 2020 年 1 月 31 日

2K+ 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始
廣告