说一下99 – 在Django中读写Session

请解释Session的概念,以及如何在Django中读写Session

  • Session(服务端, key-value)
  • Cookie(Map, key-value)
# session.py
from django.http import HttpResponse
def writeSession(request):
    request.session['name'] = 'Bill'
    request.session['age'] = 20
    return HttpResponse('writeSession')

def readSession(request):
    result = ''
    name = request.session.get('name')
    age = request.session.get('age')
    if name:
        result = '<h2>name:<font color="red">' + name + '</font></h2>'
    if age:
        result = '<h2>age:<font color="blue">' + age + '</font></h2>'
    return HttpResponse(result, content_type='text/html')

# urls.py
from django.conf.urls import url
from . import session

urlpatterns = [
    url(r'^writeSession$', session.writeSession),
    url(r'^readSession$', session.readSession)
]

正文完