Django笔记9(会话、用户和注册)

1. Cookies
(1)设置Cookie

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)获取Cookie

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.")


2.Session
(1) 打开 Sessions功能
编辑 MIDDLEWARE_CLASSES 配置,确保 MIDDLEWARE_CLASSES 中包含 ‘django.contrib.sessions.middleware.SessionMiddleware’
确认 INSTALLED_APPS 中有 ‘django.contrib.sessions’ (如果你是刚打开这个应用,别忘了运行 manage.py syncdb)
(2) 在视图中使用Session

# Set a session value:
request.session["fav_color"] = "blue"

# Get a session value -- this could be called in a different view,
# or many requests later (or both):
fav_color = request.session["fav_color"]

# Clear an item from the session:
del request.session["fav_color"]

# Check if the session has a given key:
if "fav_color" in request.session:
...

(3) 打开认证支持
根据本章早前的部分确认已经安装了session 框架,需要确认用户使用cookie,这样sesson 框架才能正常使用。
将 ‘django.contrib.auth’ 放在你的 INSTALLED_APPS 设置中,然后运行 manage.py syncdb
确认 SessionMiddleware 后面的 MIDDLEWARE_CLASSES 设置中包含 ‘django.contrib.auth.middleware.AuthenticationMiddleware’
(4) 登录和退出

from django.contrib import auth
from django.http import HttpResponseRedirect

def login(request):
    username = request.POST['username']
    password = request.POST['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/")

from django.contrib import auth

def logout(request):
    auth.logout(request)
    # Redirect to a success page.
    return HttpResponseRedirect("/account/loggedout/")

(5) 限制已登录用户的访问

from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    # ...

def user_can_vote(user):
    return user.is_authenticated() and user.has_perm("polls.can_vote")

@user_passes_text(user_can_vote, login_url="/login/")
def vote(request):
    # Code here can assume a logged-in user with the correct permission.
    ...

from django.contrib.auth.decorators import permission_required

@permission_required('polls.can_vote', login_url="/login/")
def vote(request):
    # ...

PS:由于这部分内容多属于后台权限部分,大部分代码并未测试,参考网址为:http://djangobook.py3k.cn /chapter12/,对于权限的的设置,是在数据库表里定义的(django_content_type,auth_permission),参考自动生成的数据即可有个大概的明白。值得一提的是后台User有个关联档案的功能,使得默认的user表不一定为后台服务,亦可为前台服务。这几天在思量做一个.NET版的较通用后台管理系统,并在以后改为Python及PHP版,今天看了这部分,觉得我做的Django大部分都有了,Python版的应该不必重复造轮子了,把Django研究透就好

你可能感兴趣的:(PHP,框架,django,python,配置管理)