SoFunction
Updated on 2024-10-30

Analysis of the common operations of cookies and sessions in Django project development

This article example describes the common operation of cookies and session in Django project development. Shared for your reference, as follows:

COOKIES operation

Check for the existence of cookies.

.has_key('<cookie_name>')

Get cookies.

('visits', '1')
if 'last_visit' in :
 ['last_visit']

Setting cookies.

response.set_cookie('<cookie_name>', value)

SESSION operation

Get session.

fav_color = ('fav_color', 'red')
fav_color = ['fav_color']

Set session.

['visits'] = visits

Delete session.

del ['fav_color']

If the given key does not exist in the session, a KeyError is thrown.

Determine the inclusion of session.

'fav_color' in 

Clearing the session database

python  clearsessions

Attachment:Example of Django login, register, and logout functionality based on custom cookies:

#Register
def regist(req):
  if  == 'POST':
    uf = UserForm()
    if uf.is_valid():
      # Get form data
      username = uf.cleaned_data['username']
      password = uf.cleaned_data['password']
      # Add to database
      (username= username,password=password)
      return HttpResponse('regist success!!')
  else:
    uf = UserForm()
  return render_to_response('',{'uf':uf}, context_instance=RequestContext(req))
#Login
def login(req):
  if  == 'POST':
    uf = UserForm()
    if uf.is_valid():
      # Get form user password
      username = uf.cleaned_data['username']
      password = uf.cleaned_data['password']
      #Comparison of form data retrieved with the database
      user = (username__exact = username,password__exact = password)
      if user:
        # Compare successfully, jump to index
        response = HttpResponseRedirect('/online/index/')
        # Write username to browser cookie, expiration time is 3600
        response.set_cookie('username',username,3600)
        return response
      else:
        #Rather failing, still logging in
        return HttpResponseRedirect('/online/login/')
  else:
    uf = UserForm()
  return render_to_response('',{'uf':uf},context_instance=RequestContext(req))
#Login successful
def index(req):
  username = ('username','')
  return render_to_response('' ,{'username':username})
#Exit
def logout(req):
  response = HttpResponse('logout !!')
  #Clean up the cookie that holds the username.
  response.delete_cookie('username')
  return response

I hope that what I have said in this article will help you in designing Python programs based on Django framework.