Django相关知识点笔记代码等
立即下载
资源介绍:
Django相关知识点笔记代码等
import hashlib
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from django.contrib.sessions.models import Session
from django.conf import settings
from .models import User
# Create your views here.
def reg_view(request):
if request.method=='GET':
return render(request,'user/register.html')
elif request.method=='POST':
username=request.POST['username']
password_1=request.POST['password_1']
password_2=request.POST['password_2']
if password_1!=password_2:
return HttpResponse('两次密码输入不一致')
m=hashlib.md5()
m.update(password_1.encode())
password_m=m.hexdigest()
old_users=User.objects.filter(username=username)
print(old_users)
if old_users:
return HttpResponse('--用户名已注册--')
try:
user=User.objects.create(username=username,password=password_m)
except Exception as e:
print(f'----create user error {e}')
return HttpResponse('用户名已注册')
request.session['username']=username
request.session['uid']=user.id
return HttpResponseRedirect('/index')
# Create your views here.
def login_view(request):
if request.method=='GET':
if request.session.get('username') and request.session.get('uid'):
return HttpResponseRedirect('/index')
# return HttpResponse('session 已登录')
session_key = request.COOKIES.get(settings.SESSION_COOKIE_NAME)
print(f"request.COOKIES:{request.COOKIES}")
try:
session = Session.objects.get(session_key=session_key)
if session:
data = session.get_decoded()
username = data.get('username')
uid = data.get('uid')
if username and uid:
request.session['username'] = username
request.session['uid'] = uid
return HttpResponseRedirect('/index')
# return HttpResponse('数据库 session 已登录')
except Session.DoesNotExist:
pass
c_username=request.COOKIES.get('username')
c_uid=request.COOKIES.get('uid')
if c_username and c_uid:
request.session['username']=c_username
request.session['uid']=c_uid
return HttpResponseRedirect('/index')
# return HttpResponse('cookie 已登录')
return render(request,'user/login.html')
elif request.method=='POST':
username=request.POST['username']
password=request.POST['password']
try:
user=User.objects.get(username=username)
except Exception as e:
print(f'---login tests----{e}')
return HttpResponse('----用户名或者密码错误------')
m=hashlib.md5()
m.update(password.encode())
if m.hexdigest()!=user.password:
return HttpResponse('用户名或者密码错误')
request.session['username']=username
request.session['uid']=user.id
resp=HttpResponseRedirect('/index')
if 'remember' in request.POST:
resp.set_cookie('username',username,3600*24*2)
resp.set_cookie('uid',user.id,3600*24*2)
return resp
def logout_view(request):
if 'username' in request.session:
del request.session['username']
if 'uid' in request.session:
del request.session['uid']
resp=HttpResponseRedirect('/index')
if 'username' in request.COOKIES:
resp.delete_cookie('username')
if 'uid' in request.COOKIES:
resp.delete_cookie('uid')
return resp
资源文件列表:
python_Django.zip 大约有272个文件