django的session操作

来源:互联网 发布:怎么没人去淘宝打假 编辑:程序博客网 时间:2024/06/03 02:08

登录并获取session[username]

def login(request):    m = Member.objects.get(username=request.POST['username'])  #获取当前表单的username,并从数据库中获取username的Member    if m.password == request.POST['password']:    #判断Member的password和表单输入的password是否一致        request.session['member_id'] = m.id      #如果一致,则把Member的id保存在session里,并设置为memeber_id字段,相当于session的初始化        return HttpResponse("You're logged in.") #返回到已登录    else:        return HttpResponse("Your username and password didn't match.")

注销

def logout(request):    try:        del request.session['member_id']    except KeyError:        pass    return HttpResponse("You're logged out.")

session测试

def login(request):    if request.method == 'POST':        if request.session.test_cookie_worked(): #测试浏览器是否将cookie设置为打开了            request.session.delete_test_cookie()            return HttpResponse("You're logged in.")        else:            return HttpResponse("Please enable cookies and try again.")    request.session.set_test_cookie()    return render_to_response('foo/login_form.html')

session什么时候保存了?

# Session is modified.赋值/初始化request.session['foo'] = 'bar'# Session is modified. 删除del request.session['foo']# Session is modified. 初始化/设置为空request.session['foo'] = {}# Gotcha: Session is NOT modified, because this alters# request.session['foo'] instead of request.session. 此时不会保存request.session['foo']['bar'] = 'baz'

session的一些方法

session的一些方法:__getitem__(key)  #获取session参数值(session是一个字典,key是fav_color, value是blue--假设)Example: fav_color = request.session['fav_color']__setitem__(key, value)  #设置session参数的值Example: request.session['fav_color'] = 'blue'__delitem__(key) #删除session参数的值Example: del request.session['fav_color']. This raises KeyError if the given key isn’t already in the session.__contains__(key)  #查询某参数key--fav_color  是否在session字典里面Example: 'fav_color' in request.sessionget(key, default=None) #获取session中key:fav_color的value,如果不存在则设置为redExample: fav_color = request.session.get('fav_color', 'red')pop(key)   #更新session中的key:fav_colorExample: fav_color = request.session.pop('fav_color')keys() #获取session字典中所有的keyitems() #获取session字典中所有的key:value键对setdefault() clear()# flush() 可以作为logout功能使用# Deletes the current session data from the session and deletes the session cookie. This is used if you want to ensure that the previous session data can’t be accessed again from the user’s browser

下面的懒的翻译了

set_test_cookie()test_cookie_worked()

Returns either True or False, depending on whether the user’s browser accepted the test cookie. Due to the way cookies work, you’ll have to call set_test_cookie() on a previous, separate page request. See Setting test cookies below for more information.
delete_test_cookie()

set_expiry(value)

If value is an integer, the session will expire after that many seconds of inactivity. For example, calling request.session.set_expiry(300) would make the session expire in 5 minutes.
If value is a datetime or timedelta object, the session will expire at that specific date/time. Note that datetime and timedelta values are only serializable if you are using the PickleSerializer.
If value is 0, the user’s session cookie will expire when the user’s Web browser is closed.
If value is None, the session reverts to using the global session expiry policy.

get_expiry_age()

Returns the number of seconds until this session expires. For sessions with no custom expiration (or those set to expire at browser close), this will equal SESSION_COOKIE_AGE.)

get_expiry_date()
get_expire_at_browser_close()

lear_expired()

Removes expired sessions from the session store. This class method is called by clearsessions

cycle_key()

Creates a new session key while retaining the current session data. django.contrib.auth.login() calls this method to mitigate against session fixation.
\

0 0
原创粉丝点击