Django会话cookie&session
任务描述:实现登录和退出
1.项目结构

2.源代码
urls.py
from django.conf.urls import url
from django.contrib import admin
from user import views admin.autodiscover() urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'index/', views.index),
url(r'user/regist/', views.regist),
url(r'user/login/', views.login),
url(r'user/logout/', views.logout),
]
views.py
from django.shortcuts import render
from django import forms
from django.http import HttpResponseRedirect, HttpResponse
import sqlite3
from . import models class UserForm(forms.Form):
username = forms.CharField(max_length=100)
password = forms.CharField(widget=forms.PasswordInput)
headimg = forms.FileField() class LoginForm(forms.Form):
username = forms.CharField(max_length=100)
password = forms.CharField(widget=forms.PasswordInput) def insert(user):
# 连接数据保存
models.User.objects.create(username=user.username, password=user.password, headimg=user.headimg)
return True def find_user(user):
users = models.User.objects.filter(username=user.username, password=user.password)
if users:
return True
else:
return False def regist(request):
context = {}
if request.method == 'POST':
uf = UserForm(request.POST, request.FILES)
if uf.is_valid():
username = uf.cleaned_data['username']
password = uf.cleaned_data['password']
headimg = uf.cleaned_data['headimg']
user = models.User(username=username, headimg=headimg.name, password=password)
# save headimg
fp = open('upload/' + headimg.name, 'wb')
s = headimg.read()
fp.write(s)
fp.close()
if insert(user):
return HttpResponseRedirect('/user/login') # 重定向到登录界面
else:
uf = UserForm()
context = {'uf': uf}
return render(request, 'user/regist.html', context) def login(request):
context = {}
if request.method == 'POST':
uf = LoginForm(request.POST)
if uf.is_valid():
username = uf.cleaned_data['username']
password = uf.cleaned_data['password']
user = models.User(username=username, password=password)
if find_user(user):
print('find it!')
# session
request.session['username'] = username
response = HttpResponseRedirect('/index/')
# cookie
# response.set_cookie('username', username, 3600) # 将username写入浏览器cookie,失效时间为3600
response.set_cookie('password', password, 3600) # 将password写入浏览器cookie,失效时间为3600
return response
else:
return render(request,'/user/login/',context)
else:
uf = LoginForm()
print('not find it!')
context = {'uf': uf}
return render(request, 'user/login.html', context) def logout(request):
response = HttpResponseRedirect('/user/login/')
try:
del request.session['username']
except Exception as e:
print(e)
# response.delete_cookie('username')
response.delete_cookie('password') # 删除cookie
return response def index(request):
context = {}
# session
username = request.session.get('username', 'anybody')
context['username'] = username
# cookie
if request.COOKIES:
print(request.COOKIES)
return render(request, 'index.html', context)
index,html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>index</title>
</head>
<body>
<h2>This is index page!</h2>
<p>welcome,{{username}} !</p>
<a href="/user/logout/">Logout</a>
</body>
</html>
login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>login</title>
</head>
<body>
<form method="post" action="/user/login/">
{% csrf_token %}
{{uf.as_p}}
<input type="submit" value="submit">
</form>
</body>
</html>
regist.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>regist</title>
</head>
<body>
<h3>regist</h3>
<hr>
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{uf.as_p}}
<input type="submit" value="submit">
</form>
</body>
</html>
models.py
from django.db import models class User(models.Model):
username = models.CharField(max_length=100)
password = models.CharField(max_length=20, default='123456')
headimg = models.FileField() def __str__(self):
return self.username + ',' + self.password + ',' + self.headimg.name
3.运行测试
未登录访问:

登录后访问:


退出

Django会话cookie&session的更多相关文章
- day09 Django: 组件cookie session
day09 Django: 组件cookie session 一.cookie和session都是会话跟踪技术 1.什么是会话 可以理解为客户端和服务端之间的一次会 ...
- django - 总结 - cookie|session
Cookie是通过HTTP请求和响应头在客户端和服务器端传递的. 在Web开发中,使用session来完成会话跟踪,session底层依赖Cookie技术. --------------------- ...
- python框架之Django(7)-Cookie&Session使用
Cookie 添加 response.set_cookie 添加明文cookie response.set_cookie(key, value='', max_age=None, expires=No ...
- python 全栈开发,Day76(Django组件-cookie,session)
昨日内容回顾 1 json 轻量级的数据交换格式 在python 序列化方法:json.dumps() 反序列化方法:json.loads() 在JS中: 序列化方法:JSON.stringfy() ...
- Django中cookie&session的实现
1.什么叫Cookie Cookie翻译成中文是小甜点,小饼干的意思.在HTTP中它表示服务器送给客户端浏览器的小甜点.其实Cookie是key-value结构,类似于一个python中的字典.随着服 ...
- Django之cookie+session
前言 HTTP协议 是短连接.且状态的,所以在客户端向服务端发起请求后,服务端在响应头 加入cokie响应给浏览器,以此记录客户端状态: cook是来自服务端,保存在浏览器的键值对,主要应用于用户登录 ...
- Django之cookie&session
cookie Cookie 是在 HTTP 协议下,服务器或脚本可以维护客户工作站上信息的一种方式.Cookie 是由 Web 服务器保存在用户浏览器(客户端)上的小文本文件,它可以包含有关用户的信息 ...
- django框架--cookie/session
目录 一.http协议无状态问题 二.会话跟踪技术--cookie 1.对cookie的理解 2.cookie的使用接口 3.cookie的属性 4.使用cookie的问题 三.会话跟踪技术--ses ...
- Django组件-cookie,session
昨日内容回顾: json 轻量级的数据交换格式 在python 序列化方法:json.dumps() 反序列化方法:json.loads() 在JS中: 序列化方法:JSON.stringfy() 反 ...
随机推荐
- 3.1 Broker Configs 官网剖析(博主推荐)
不多说,直接上干货! 一切来源于官网 http://kafka.apache.org/documentation/ 3.1 Broker Configs 3.1 broker配置 The essent ...
- 关于Promise详解
异步回调 回调地狱 在需要多个操作的时候,会导致多个回调函数嵌套,导致代码不够直观,就是常说的回调地狱 并行结果 如果几个异步操作之间并没有前后顺序之分,但需要等多个异步操作都完成后才能执行后续的任务 ...
- 【Codeforces Round #453 (Div. 2) C】 Hashing Trees
[链接] 我是链接,点我呀:) [题意] 在这里输入题意 [题解] 显然只有当a[i]和a[i-1]都大于1的时候才会有不同的情况. a[i] >= a[i-1] 且a[i-1]>=2 则 ...
- HDU 4869 Turn the pokers(思维+组合公式+高速幂)
pid=4869" target="_blank">Turn the pokers 大意:给出n次操作,给出m个扑克.然后给出n个操作的个数a[i],每一个a[i] ...
- Gmail 收信的一些规则
Gmail 收信的一些规则 用 apache+php+MDaemon 调试 mail2www 时,发往gmail的邮件失败, 提示: Our system detected an illegal at ...
- Spark 概念学习系列之Spark存储管理机制
Spark存储管理机制 概要 01 存储管理概述 02 RDD持久化 03 Shuffle数据存储 04 广播变量与累加器 01 存储管理概述 思考: RDD,我们可以直接使用而无须关心它的实现细节, ...
- C# foreach 循环遍历数组
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Cons ...
- Maven学习总结(15)——Maven 项目中pom.xml详解
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2 ...
- UVA 11646 - Athletics Track || UVA 11817 - Tunnelling the Earth 几何
题目大意: 两题几何水题. 1.UVA 11646 - Athletics Track 如图,体育场的跑道一圈400米,其中弯道是两段半径相同的圆弧,已知矩形的长宽比例为a:b,求长和宽的具体数值. ...
- AUC(Area Under roc Curve )计算及其与ROC的关系
转载: http://blog.csdn.net/chjjunking/article/details/5933105 让我们从头说起,首先AUC是一种用来度量分类模型好坏的一个标准.这样的标准其实有 ...