Django2 + MySQL 存储session 会话值
小虾米
阅读:650
2021-03-31 18:17:36
评论:0
第一步:创建项目
第二步:创建应用
第三步:项目setting.py 配置
1、启用session记录中间件和注释cfsf 中间件
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
# 启用session 会话中间件
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
# 禁用crsf 中间件
# 'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
2、启用session 存储应用
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
# 启用 sessio 数据库存储
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
3、数据库设置
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'student',
'USER': 'root',
'PASSWORD': '123456',
'HOST': '127.0.0.1',
'PORT': '3306',
'OPTIONS': {'charset': 'utf8mb4'},
}
}
4、设置模板路径
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
# 绝对路径 模板文件配置
'DIRS': ['E:/python_workspace/djangosite/template'],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
5、配置显示和时区选择
# 配置显示中文和时间区间
LANGUAGE_CODE = 'zh-hans'
TIME_ZONE = 'Asia/Shanghai'
USE_I18N = True
USE_L10N = True
USE_TZ = True
第四步:数据库数据同步,执行如下指令:
在终端Terminal 项目目录下执行数据表更新命令:
python manage.py makemigrations
python manage.py migrate
查看相关数据库是否生成:
django_session表
第五步:编写应用视图函数和应用路由函数
/sessionapp/views.py
from django.shortcuts import render, render_to_response
from django.http import HttpResponse, HttpResponseRedirect
from django import forms
class UserForm(forms.Form):
username = forms.CharField()
password = forms.CharField()
# 用户登录
def login(req):
if req.method == "POST":
uf = UserForm(req.POST)
if uf.is_valid():
username = uf.cleaned_data['username']
password = uf.cleaned_data['password']
# 把获取表单的用户名传递给session对象
req.session['username'] = username
req.session['password'] = password
return HttpResponseRedirect('/sessionapp/index/')
else:
uf = UserForm()
return render_to_response('login.html', {'uf': uf})
# 登录之后跳转页
def index(req):
username = req.session.get('username', 'anybody')
password = req.session.get('password', '')
return render_to_response('index.html', {'username': username})
# 注销动作
def logout(req):
del req.session['username'] # 删除session
del req.session['password']
return HttpResponse('logout ok!')
/sessionapp/url.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^login/$', views.login),
url(r'^index/$', views.index),
url(r'^logout/$', views.logout),
]
第六步:编写项目路由函数
/djangosite/url.py
"""djangosite URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from django.conf.urls import include
urlpatterns = [
path('admin/', admin.site.urls),
path('sessionapp/', include('sessionapp.urls')),
]
第七步:编辑模板文件:
index.html
<div>
<h1>welcome {
{username}}</h1>
<a href="/sessionapp/logout">logout</a>
</div>
login.html
<form method = 'post'>
{
{uf.as_p}}
<input type="submit" value = "ok"/>
</form>
项目结构图:
django_session表记录:
声明
1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。