当前位置:   article > 正文

后台接口搭建步骤Django框架(pycharm社区版一样适用)

后台接口搭建步骤Django框架(pycharm社区版一样适用)

第一步:创建项目

打开命令行界面,输入以下命令:

django-admin startproject (项目名称)

第二步:创建应用

进入项目根目录,确保与manage.py文件处于同一级,输入下述命令:

python manage.py startapp (应用名称)

第三步:创建数据库

使用Navicat创建数据库(此处不做强行要求,能实现创建数据库即可)

第四步:配置数据库链接

在与项目同名的文件夹下,找到并打开settings.py文件

修改配置如下:

  1. DATABASES = {
  2. 'default': {
  3. 'ENGINE': 'django.db.backends.mysql', # 数据库引擎
  4. 'NAME': 'mysite', # 数据库名,先前创建的
  5. 'USER': 'root', # 用户名,可以自己创建用户
  6. 'PASSWORD': '', # 密码
  7. 'HOST': '127.0.0.1', # mysql服务所在的主机ip
  8. 'PORT': '3306' # mysql服务端口
  9. }
  10. }

在INSTALLED_APPS中添加你的应用

  1. INSTALLED_APPS = [
  2. 'django.contrib.admin',
  3. 'django.contrib.auth',
  4. 'django.contrib.contenttypes',
  5. 'django.contrib.sessions',
  6. 'django.contrib.messages',
  7. 'django.contrib.staticfiles',
  8. '你的应用名称'
  9. ]

注释掉csrf中间件

  1. MIDDLEWARE = [
  2. 'django.middleware.security.SecurityMiddleware',
  3. 'django.contrib.sessions.middleware.SessionMiddleware',
  4. 'django.middleware.common.CommonMiddleware',
  5. # 'django.middleware.csrf.CsrfViewMiddleware',
  6. 'django.contrib.auth.middleware.AuthenticationMiddleware',
  7. 'django.contrib.messages.middleware.MessageMiddleware',
  8. 'django.middleware.clickjacking.XFrameOptionsMiddleware',
  9. ]

第五步:配置路由

在与项目同名的文件夹下,找到并打开urls.py文件

修改配置如下:

  1. from django.urls import path,include
  2. urlpatterns = [
  3. # path('admin/', admin.site.urls),
  4. path('api/', include('你的应用的名字.urls'))
  5. ]

第六步:创建数据库表

在应用文件夹下,找到并打开models.py

定义class类,每个类对应一张数据库表

  1. class Devices(models.Model):
  2. dev_code = models.CharField(max_length=24)
  3. dev_name = models.CharField(max_length=50)
  4. address = models.CharField(max_length=100)
  5. status = models.BooleanField()
  6. class Records(models.Model):
  7. dev = models.ForeignKey(to=Devices,on_delete=models.CASCADE)
  8. duration = models.IntegerField(default=0)
  9. amount = models.DecimalField(max_digits=10, decimal_places=2)
  10. create_time = models.DateTimeField(auto_created=True)

运行(数据迁移,创建表)

1)python manage.py makemigrations

2)python manage.py migrate

第七步:编写数据接口

在应用文件夹下,找到并打开views.py

定义class类,每个类就是一个接口,有get(查询)、post(添加)、put(修改)、delete(删除)

  1. from django.http import JsonResponse
  2. from django.views import View
  3. from api.models import *
  4. from datetime import datetime
  5. import math
  6. import json
  7. # Create your views here.
  8. class DevicesApi(View):
  9. def get(self, request):
  10. pagesize = 5
  11. result = Devices.objects.filter()
  12. params = request.GET
  13. keyword = params.get('key', '')
  14. page = params.get('page', '')
  15. sort = params.get('sort', '0')
  16. if(keyword != ''):
  17. result = result.filter(community_name__contains=keyword)
  18. if(sort == '1'):
  19. result = result.order_by('-id')
  20. elif(sort == '2'):
  21. result = result.order_by('id')
  22. records = result.count()
  23. print(page+'a')
  24. if(page != ''):
  25. page = int(page)
  26. start = (page - 1) * pagesize
  27. end = page * pagesize
  28. result = result[start:end]
  29. total = math.ceil(records / pagesize)
  30. data = []
  31. for item in result:
  32. data.append({
  33. 'id': item.id,
  34. 'dev_code': item.dev_code,
  35. 'community_name': item.community_name,
  36. 'dev_address': item.dev_address,
  37. 'dev_status': item.dev_status
  38. })
  39. return JsonResponse({'code': 200, 'data':data, 'total': total, 'page': page})
  40. def post(self,request):
  41. data = json.loads(request.body)
  42. # print(data)
  43. obj = Devices()
  44. obj.dev_code = data['dev_code']
  45. obj.community_name = data['community_name']
  46. obj.dev_address = data['dev_address']
  47. obj.dev_status = 0
  48. obj.save()
  49. return JsonResponse({'code': 200})
  50. class DevicesDel(View):
  51. def post(self, request):
  52. data = json.loads(request.body)
  53. # print(data)
  54. Devices.objects.filter(id__in=data).delete()
  55. return JsonResponse({'code': 200})
  56. class DevicesEdit(View):
  57. def get(self, request):
  58. devID = int(request.GET.get('id',0))
  59. if(devID>0):
  60. obj = Devices.objects.get(id=devID)
  61. if(obj.dev_status):
  62. obj.dev_status = 0
  63. else:
  64. obj.dev_status = 1
  65. obj.save()
  66. return JsonResponse({'code': 200})
  67. class DevicesInfo(View):
  68. def get(self, request):
  69. devID = int(request.GET.get('id', 0))
  70. result = {}
  71. if(devID > 0):
  72. obj = Devices.objects.get(id=devID)
  73. # print(obj)
  74. result = {'id': obj.id, 'dev_code': obj.dev_code, 'community_name': obj.community_name, 'dev_address': obj.dev_address, 'dev_status': obj.dev_status}
  75. return JsonResponse({'code': 200, 'data': result})
  76. class RecordApi(View):
  77. def post(self, request):
  78. data = json.loads(request.body)
  79. obj = Records()
  80. obj.dev_id_id = data['dev_id']
  81. obj.use_times = data['use_times']
  82. obj.amount = data['amount']
  83. obj.create_time = datetime.now()
  84. obj.save()
  85. return JsonResponse({'code': 200})
  86. def get(self, request):
  87. pagesize = 5
  88. result = Records.objects.filter().order_by('-id')
  89. params = request.GET
  90. page = params.get('page', '')
  91. records = result.count()
  92. if (page != ''):
  93. page = int(page)
  94. start = (page - 1) * pagesize
  95. end = page * pagesize
  96. result = result[start:end]
  97. total = math.ceil(records / pagesize)
  98. data = []
  99. for item in result:
  100. data.append({
  101. 'id': item.id,
  102. 'dev_code': item.dev_id.dev_code,
  103. 'community_name': item.dev_id.community_name,
  104. 'dev_address': item.dev_id.dev_address,
  105. 'dev_status': item.dev_id.dev_status,
  106. 'use_times': item.use_times,
  107. 'amount': item.amount,
  108. 'dev_id': item.dev_id_id
  109. })
  110. return JsonResponse({'code': 200, 'data': data, 'total': total, 'page': page})

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Gausst松鼠会/article/detail/642341
推荐阅读
相关标签
  

闽ICP备14008679号