Django前后端分离之后端实践2

小实践:实现用户登录、注销及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.name

class 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 views


urlpatterns = [
    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,login

class 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):
        pass
        import 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):
        pass

    def 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 status
            book.status = True
            book.save()
            # add record
            Record.objects.create(name=name, book=book)
        return JsonResponse({'code': 1000, 'messages': "出借成功"})
相关推荐
J不A秃V头A5 分钟前
Python爬虫:获取国家货币编码、货币名称
开发语言·爬虫·python
阿斯卡码1 小时前
jupyter添加、删除、查看内核
ide·python·jupyter
FIN技术铺3 小时前
Redis集群模式之Redis Sentinel vs. Redis Cluster
数据库·redis·sentinel
埃菲尔铁塔_CV算法4 小时前
图像算法之 OCR 识别算法:原理与应用场景
图像处理·python·计算机视觉
CodingBrother4 小时前
MySQL 中的 `IN`、`EXISTS` 区别与性能分析
数据库·mysql
封步宇AIGC4 小时前
量化交易系统开发-实时行情自动化交易-3.4.2.Okex行情交易数据
人工智能·python·机器学习·数据挖掘
封步宇AIGC4 小时前
量化交易系统开发-实时行情自动化交易-2.技术栈
人工智能·python·机器学习·数据挖掘
代码小鑫4 小时前
A027-基于Spring Boot的农事管理系统
java·开发语言·数据库·spring boot·后端·毕业设计
小小不董5 小时前
Oracle OCP认证考试考点详解082系列16
linux·运维·服务器·数据库·oracle·dba
甄臻9245 小时前
Windows下mysql数据库备份策略
数据库·mysql