Django sessions 詳解--part I: Cookies

所謂cookie其實就是有服務器端發送到客戶端的屬性字符串,而後客戶端再返回給服務器端。它裏面包含了一些用戶的基本信息。cookie中的信息對客戶端是不透名的,它只在服務器端使用。html

下面,咱們來看看在Django中使用cookie。python

首先來看看在python中使用cookie

from BaseHTTPServer import HTTPServer
from SimpleHTTPServer import SimpleHTTPRequestHandler
import Cookie瀏覽器

class MyRequestHandler(SimpleHTTPRequestHandler):
    def do_GET(self):
        content = "<html><body>Path is: %s</body></html>" % self.path
        self.send_response(200)
        self.send_header('Content-type', 'text/html')
        self.send_header('Content-length', str(len(content)))安全

        cookie = Cookie.SimpleCookie()
        cookie['id'] = 'some_value_42'服務器

        self.wfile.write(cookie.output())
        self.wfile.write('\r\n')cookie

        self.end_headers()
        self.wfile.write(content)session

server = HTTPServer(('', 59900), MyRequestHandler)
server.serve_forever()性能

這是一個很是簡單的使用cookie的例子,它展現了瀏覽器請求的路徑信息。同時,它也設置了一個cookie,服務器的相應頭部應該會包含相似下面的信息:orm

Set-Cookie: id=some_value_42server

python中的cookie模塊提供了load方法用來解析cookie,這裏就再也不贅述。 下面來看看在Django中的cookie。

Django中的cookie設置比較煩瑣,下面的方法展現了檢測一個httprequest中是否有cookie,若是沒有服務器會返回一個cookie給瀏覽器,以便下次訪問中使用它:

def test_cookie(request):
    if 'id' in request.COOKIES:
        cookie_id = request.COOKIES['id']
        return HttpResponse('Got cookie with id=%s' % cookie_id)
    else:
        resp = HttpResponse('No id cookie! Sending cookie to client')
        resp.set_cookie('id', 'some_value_99')
        return resp

從上能夠看出cookie被設置在一個httprequest中的類dict屬性中,咱們能夠直接訪問它。

Django中cookie的執行

Django的應用一般都是經過WSGI部署的,因此咱們重點看看WSGI後臺上的執行。以Django1.3爲例,WSGIRequest(繼承自http.Request)類中,咱們能夠看到cookie被設置成隱藏屬性存放在self._cookies,以下:

def _get_cookies(self):
    if not hasattr(self, '_cookies'):
        self._cookies = http.parse_cookie(self.environ.get('HTTP_COOKIE', ''))
    return self._cookies

每一個WSGI specification實例都有cookie屬性,但並不是每一個請求都須要cookie,因此在不準要cookie的時候,咱們就不須要對它進行解析。上面的代碼中咱們提到一個方法:http.parse_cookie,它又是什麼?它是 Django’s HTTP module一個通用方法

def parse_cookie(cookie):
    if cookie == '':
        return {}
    if not isinstance(cookie, Cookie.BaseCookie):
        try:
            c = SimpleCookie()
            c.load(cookie, ignore_parse_errors=True)
        except Cookie.CookieError:
            # Invalid cookie
            return {}
    else:
        c = cookie
    cookiedict = {}
    for key in c.keys():
        cookiedict[key] = c.get(key).value
    return cookiedict

它就是經過標準庫中的Cookie模塊來解析cookie的。 在一個httpresponse中設置cookie要經過set_cookie方法。它會將設置的cookie寫進self.cookies屬性。而WSGIHandler將會把相關的cookie信息添加在httpresponse的header中。

結束語

其實cookie在python和Django中的使用是很是簡單的,可是處於安全性能的考慮,仍是不建議直接在Django中使用cookie,而是推薦使用更高級的sessions。

# 做者微博:http://weibo.com/amaozhao

相關文章
相關標籤/搜索