Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Cách thiết lập (setup) cookies trong Python CGI Programming?

Thiết lập Cookies

Rất dễ gửi cookies đến trình duyệt. Cookies gửi kèm HTTP Header trước trường Content-type. Giả sử muốn set UserID và Password làm cookies:

#!/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"
...........Nội dung HTML còn lại....

Từ ví dụ, hiểu cách set cookies. Dùng HTTP header Set-Cookie. Các thuộc tính Expires, Domain, Path là tùy chọn. Lưu ý: cookies phải set trước dòng "Content-type:text/html\r\n\r\n".