标签:body doctype com namespace 首页 项目 读写 render type
项INSTALLED_APPS列表中添加:
‘django.contrib.sessions‘,
项MIDDLEWARE_CLASSES列表中添加:
‘django.contrib.sessions.middleware.SessionMiddleware‘,
from django.shortcuts import render, redirect
from django.core.urlresolvers import reverse
def index(request):
uname = request.session.get(‘uname‘)
return render(request, ‘booktest/index.html‘, {‘uname‘: uname})
def login(request):
return render(request, ‘booktest/login.html‘)
def login_handle(request):
request.session[‘uname‘] = request.POST[‘uname‘]
return redirect(reverse(‘main:index‘))
def logout(request):
# request.session[‘uname‘] = None
# del request.session[‘uname‘]
# request.session.clear()
request.session.flush()
return redirect(reverse(‘main:index‘))
主url:
from django.conf.urls import include, url
urlpatterns = [
url(r‘^‘, include(‘booktest.urls‘, namespace=‘main‘))
]
应用url:
from django.conf.urls import url
from . import views
urlpatterns = [
url(r‘^$‘, views.index, name=‘index‘),
url(r‘login/$‘, views.login, name=‘login‘),
url(r‘login_handle/$‘, views.login_handle, name=‘login_handle‘),
url(r‘logout/$‘, views.logout, name=‘logout‘)
]
<!DOCTYPE html>
<html>
<head>
<title>首页</title>
</head>
<body>
你好:{{uname}}
<hr/>
<a href="{%url ‘main:login‘%}">登录</a>
<hr/>
<a href="{%url ‘main:logout‘%}">退出</a>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>登录</title>
</head>
<body>
<form method="post" action="/login_handle/">
<input type="text" name="uname"/>
<input type="submit" value="登录"/>
</form>
</body>
</html>
def login_handle(request):
request.session[‘uname‘] = request.POST[‘uname‘]
# request.session.set_expiry(10)
# request.session.set_expiry(timedelta(days=5))
# request.session.set_expiry(0)
# request.session.set_expiry(None)
return redirect(reverse(‘main:index‘))
SESSION_ENGINE=‘django.contrib.sessions.backends.db‘
SESSION_ENGINE=‘django.contrib.sessions.backends.cache‘
SESSION_ENGINE=‘django.contrib.sessions.backends.cached_db‘
pip install django-redis-sessions
SESSION_ENGINE = ‘redis_sessions.session‘
SESSION_REDIS_HOST = ‘localhost‘
SESSION_REDIS_PORT = 6379
SESSION_REDIS_DB = 0
SESSION_REDIS_PASSWORD = ‘‘
SESSION_REDIS_PREFIX = ‘session‘
启动:sudo redis-server /etc/redis/redis.conf
停止:sudo redis-server stop
重启:sudo redis-server restart
redis-cli:使用客户端连接服务器
keys *:查看所有的键
get name:获取指定键的值
del name:删除指定名称的键
标签:body doctype com namespace 首页 项目 读写 render type
原文地址:https://www.cnblogs.com/joshuazc/p/9534176.html