//cookie不安全
1某饰、讀寫cookie: request.COOKIES
def show_color(request):
if "favorite_color" in request.COOKIES:
return HttpResponse("Your favorite color is %s" % request.COOKIES["favorite_color"])
else:
return HttpResponse("You don't have a favorite color.")
//response.set_cookie:參數(shù)包括max_age,expires,path,domain,False
def set_color(request):
if "favorite_color" in request.GET:
# Create an HttpResponse object...
response = HttpResponse("Your favorite color is now %s" % request.GET["favorite_color"])
# ... and set a cookie on the response
response.set_cookie("favorite_color",
request.GET["favorite_color"])
return response
else:
return HttpResponse("You didn't give a favorite color.")
2、使用session:
settings.py
編輯 MIDDLEWARE_CLASSES 配置诫尽,確保 MIDDLEWARE_CLASSES 中包含 'django.contrib.sessions.middleware.SessionMiddleware'炬守。
確認(rèn) INSTALLED_APPS 中有 'django.contrib.sessions' (同時需要同步數(shù)據(jù)庫)
--
request.session["fav_color"] = "blue"
fav_color = request.session["fav_color"]
del request.session["fav_color"]
if "fav_color" in request.session:
////使用
def post_comment(request):
if request.method != 'POST':
raise Http404('Only POSTs are allowed')
if 'comment' not in request.POST:
raise Http404('Comment not submitted')
if request.session.get('has_commented', False):
return HttpResponse("You've already commented.")
c = comments.Comment(comment=request.POST['comment'])
c.save()
request.session['has_commented'] = True
return HttpResponse('Thanks for your comment!')
3减途、測試對方是否支持cookie鳍置;request.session.test_cookie_worked()
def login(request):
# If we submitted the form...
if request.method == 'POST':
# Check that the test cookie worked (we set it below):
if request.session.test_cookie_worked():
# The test cookie worked, so delete it.
request.session.delete_test_cookie()
# In practice, we'd need some logic to check username/password
# here, but since this is an example...
return HttpResponse("You're logged in.")
# The test cookie failed, so display an error message. If this
# were a real site, we'd want to display a friendlier message.
else:
return HttpResponse("Please enable cookies and try again.")
# If we didn't post, send the test cookie along with the login form.
request.session.set_test_cookie()
return render_to_response('foo/login_form.html')
4墓捻、session類:
from django.contrib.sessions.models import Session
s = Session.objects.get(pk='2b1189a188b44ad18c35e113ac6ceead')
s.expire_date
datetime.datetime(2005, 8, 20, 13, 35, 12)
s.session_data
'KGRwMQpTJ19hdXRoX3VzZXJfaWQnCnAyCkkxCnMuMTExY2ZjODI2Yj...'
s.get_decoded()
{'user_id': 42}
如果cookie沒有設(shè)置過期時間,當(dāng)用戶關(guān)閉瀏覽器的時候撤卢,cookie就自動過期了梧兼。 你可以改變 SESSION_EXPIRE_AT_BROWSER_CLOSE 的設(shè)置來控制session框架的這一行為。
缺省情況下渡紫, SESSION_EXPIRE_AT_BROWSER_CLOSE 設(shè)置為 False 考赛,這樣颜骤,會話cookie可以在用戶瀏覽器中保持有效達(dá) SESSION_COOKIE_AGE 秒(缺省設(shè)置是兩周,即1,209,600 秒)八孝。 如果你不想用戶每次打開瀏覽器都必須重新登陸的話,用這個參數(shù)來幫你子姜。
SESSION_COOKIE_DOMAIN 作用域
SESSION_COOKIE_NAME cookie名字
SESSION_COOKIE_SECURE 是否通過HTTPS傳輸
Session 數(shù)據(jù)存在數(shù)據(jù)庫表 django_session 中
5楼入、auth模塊
將 'django.contrib.auth' 放在你的 INSTALLED_APPS 設(shè)置中浅辙,然后運行 manage.py syncdb以創(chuàng)建對應(yīng)的數(shù)據(jù)庫表。
確認(rèn) SessionMiddleware 后面的 MIDDLEWARE_CLASSES 設(shè)置中包含 'django.contrib.auth.middleware.AuthenticationMiddleware' SessionMiddleware。
//調(diào)用:request.user
request.user.is_authenticated()
request.user對象的方法
username,first_name,last_name,email,password,is_staff,is_active,is_superuser,last_login,date_joined.
is_authenticated() is_anonymous() get_full_name() set_password() check_password()
get_group_permissions() get_all_permissions() has_perm() has_perms() has_module_perms() get_and_delete_messages() email_user()
Set a user's groups:
myuser.groups = group_list
Add a user to some groups:
myuser.groups.add(group1, group2,...)
Remove a user from some groups:
myuser.groups.remove(group1, group2,...)
Remove a user from all groups:
myuser.groups.clear()
Permissions work the same way
myuser.permissions = permission_list
myuser.permissions.add(permission1, permission2, ...)
myuser.permissions.remove(permission1, permission2, ...)
myuser.permissions.clear()
7\
from django.contrib import auth
user=auth.authenticate(username='',password='')
if user is not None:
8泽腮、login_view
from django.contrib import auth
def login_view(request):
username = request.POST.get('username', '')
password = request.POST.get('password', '')
user = auth.authenticate(username=username, password=password)
if user is not None and user.is_active:
# Correct password, and the user is marked "active"
auth.login(request, user)
# Redirect to a success page.
return HttpResponseRedirect("/account/loggedin/")
else:
# Show an error page
return HttpResponseRedirect("/account/invalid/")
9诊赊、logout_view
from django.contrib import auth
def logout_view(request):
auth.logout(request)
# Redirect to a success page.
return HttpResponseRedirect("/account/loggedout/")
10府瞄、 urls.py
from django.contrib.auth.views import login, logout
urlpatterns = patterns('',
# existing patterns here...
(r'^accounts/login/', logout),
)
11遵馆、registragiton/login.html login_out.html
{% extends "base.html" %}
{% block content %}
{% if form.errors %}
<p class="error">Sorry, that's not a valid username or password</p>
{% endif %}
<form action="" method="post">
<label for="username">User name:</label>
<input type="text" name="username" value="" id="username">
<label for="password">Password:</label>
<input type="password" name="password" value="" id="password">
<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next|escape }}" />
</form>
{% endblock %}
12 裝飾器
from django.contrib.auth.decorators import login_required
@login_required
13货邓、登錄與權(quán)限
def vote(request):
if request.user.is_authenticated() and request.user.has_perm('polls.can_vote')):
# vote here
else:
return HttpResponse("You can't vote in this poll.")
===@user_passes_test(user_can_vote,login_url="/login/")
def user_can_vote(user):
return user.is_authenticated() and user.has_perm("polls.can_vote")
@user_passes_test(user_can_vote, login_url="/login/")
def vote(request):
# Code here can assume a logged-in user with the correct permission.
14、權(quán)限:@permission_required
from django.contrib.auth.decorators import permission_required
@permission_required('polls.can_vote', login_url="/login/")
def vote(request):
# ...
15职辨、創(chuàng)建用戶:
from django.contrib.auth.models import User
user = User.objects.create_user(username='john',
... email='jlennon@beatles.com',
... password='glass onion')
user.is_staff = True
user.save()
修改密碼
user = User.objects.get(username='john')
user.set_password('goo goo goo joob')
user.save()
16舒裤、
{% if user.is_authenticated %}
<p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
<p>Welcome, new user. Please log in.</p>
{% endif %}
17觉吭、檢查權(quán)限
{% if perms.polls %}
<p>You have permission to do something in the polls app.</p>
{% if perms.polls.can_vote %}
<p>You can vote!</p>
{% endif %}
{% else %}
<p>You don't have permission to do anything in the polls app.</p>
{% endif %}
18、用戶消息
def create_playlist(request, songs):
# Create the playlist with the given songs.
# ...
request.user.message_set.create(
message="Your playlist was added successfully."
)
return render_to_response("playlists/create.html",
context_instance=RequestContext(request))
{% if messages %}
<ul>
{% for message in messages %}
<li>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}