• 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.运行测试

    未登录访问:

    登录后访问:

    退出

  • 相关阅读:
    html表单的创建
    mysql数据库连接标准操作
    关于Apache+MySQL+PHP下载及配置注意事项
    两个范例
    Stack类
    Collections类集
    key可以重复的map集合:IdentityHashMap
    foreach对集合的输出作用
    ListIterator接口
    【官方方法】xcode7免证书真机调试
  • 原文地址:https://www.cnblogs.com/jasonhaven/p/7490572.html
Copyright © 2020-2023  润新知