小实践:实现用户登录、注销及ORM管理功能、事务开启小实践
models.py
class Books(models.Model):id = models.CharField(primary_key=True,max_length=20,verbose_name="图书ID")name = models.CharField(max_length=20,verbose_name='图书名称')status = models.BooleanField(default=False,verbose_name='是否出借',blank=True)class Meta:db_table = 'books'verbose_name = '图书表'def __str__(self):return self.nameclass Record(models.Model):book = models.ForeignKey('Books',on_delete=models.CASCADE,verbose_name="图书")name = models.CharField(max_length=20,verbose_name='借书姓名')s_time = models.DateTimeField(auto_created=True,verbose_name='借书时间',auto_now=True) # auto_created 自动创建当前时间e_time = models.DateTimeField(auto_created=True,verbose_name='还书时间',auto_now=True) # auto_now 任意一个字段变更都会自动更新时间state = models.BooleanField(default=False,verbose_name='是否归还',blank=True)class Meta:db_table = 'records'verbose_name = '图书记录'
urls.py[注意:路由结尾要记得加$符号,负责会匹配其他的视图函数]
from django.contrib import admin
from django.urls import path,re_path,include
from news import viewsurlpatterns = [path('admin/', admin.site.urls),re_path(r'^news/',include('news.urls')),re_path(r'logout/$',views.LogoutView.as_view()),re_path(r'login/$',views.LoginView.as_view()),re_path(r'book/$',views.BookView.as_view()),re_path(r'book/hanlde/$',views.RecordView.as_view())
]
用户登录注销:
from django.http import HttpResponse,JsonResponse
from django.views import View
from django.contrib.auth import authenticate,logout,loginclass LogoutView(View):def get(self,request):logout(request)return JsonResponse({'code':200,'message':'已退出登录'},status=200)class LoginView(View):def post(self,request):username = request.POST.get('username')password = request.POST.get('password')user = authenticate(request,username=username,password=password)if user is not None:login(request,user)return JsonResponse({'code':200,'message':'登录成功'})else:return JsonResponse({'code':400,'message':'登录失败'})
admin.py 可后台查看数据
from .models import Books,Record
class BookAdmin(admin.ModelAdmin):list_display = ['id','name','status']class RecordAdmin(admin.ModelAdmin):list_display = ['id','book','name','s_time','e_time','state']admin.site.register(Books,BookAdmin)
admin.site.register(Record,RecordAdmin)
ORM功能的增删改成实现
class BookView(View):def get(self,request):if not request.user.is_authenticated:return JsonResponse({'code':2002,'messages':"认证失败你没有权限访问,请重新登录"})bs= Books.objects.all()result = []for i in bs:item = dict(id=i.id,name=i.name,status=i.status)result.append(item)return JsonResponse({'code':200,'data':result,'message':'ok'},safe=False)def post(self,request):passimport json# param =request.POST if len(request.POST)> 0 else json.loads(request.body.decode())id = request.POST.get('id')name = request.POST.get('name')try:Books.objects.create(id=id,name=name)except Exception as e:return JsonResponse({'code':2001,'message':'书籍编号已存在,异常:{}'.format(e)},safe=False)else:return JsonResponse({'code':1001,'message':'添加成功'},safe=False)def delete(self,request):id = request.POST.get('id')if not id:return JsonResponse({'code':1001,'message':'删除失败'})try:book = Books.objects.get(id=id)except Exception as e:return JsonResponse({'code': 1001, 'message': '删除失败:{}'.format(e)})else:book.delete()return JsonResponse({'code': 200, 'message': '删除成功'})
应用结果:
事务实现:
class RecordView(View):def get(self, request):passdef post(self, request):book_id = request.POST.get('id')name = request.POST.get('name')try:book = Books.objects.get(id=book_id)except Exception as e:return JsonResponse({'code': 2001, 'messages': "{}".format(e)})if book.status:return JsonResponse({'code': 2001, 'messages': "该书籍已借书,请确认书籍的状态是否已出借"})with transaction.atomic():# update statusbook.status = Truebook.save()# add recordRecord.objects.create(name=name, book=book)return JsonResponse({'code': 1000, 'messages': "出借成功"})