赞
踩
第一步:创建项目
打开命令行界面,输入以下命令:
django-admin startproject (项目名称)
第二步:创建应用
进入项目根目录,确保与manage.py
文件处于同一级,输入下述命令:
python manage.py startapp (应用名称)
第三步:创建数据库
使用Navicat创建数据库(此处不做强行要求,能实现创建数据库即可)
第四步:配置数据库链接
在与项目同名的文件夹下,找到并打开settings.py文件
修改配置如下:
- DATABASES = {
- 'default': {
- 'ENGINE': 'django.db.backends.mysql', # 数据库引擎
- 'NAME': 'mysite', # 数据库名,先前创建的
- 'USER': 'root', # 用户名,可以自己创建用户
- 'PASSWORD': '', # 密码
- 'HOST': '127.0.0.1', # mysql服务所在的主机ip
- 'PORT': '3306' # mysql服务端口
- }
- }
在INSTALLED_APPS中添加你的应用
- INSTALLED_APPS = [
- 'django.contrib.admin',
- 'django.contrib.auth',
- 'django.contrib.contenttypes',
- 'django.contrib.sessions',
- 'django.contrib.messages',
- 'django.contrib.staticfiles',
- '你的应用名称'
- ]
注释掉csrf中间件
- MIDDLEWARE = [
- 'django.middleware.security.SecurityMiddleware',
- 'django.contrib.sessions.middleware.SessionMiddleware',
- 'django.middleware.common.CommonMiddleware',
- # 'django.middleware.csrf.CsrfViewMiddleware',
- 'django.contrib.auth.middleware.AuthenticationMiddleware',
- 'django.contrib.messages.middleware.MessageMiddleware',
- 'django.middleware.clickjacking.XFrameOptionsMiddleware',
- ]
第五步:配置路由
在与项目同名的文件夹下,找到并打开urls.py文件
修改配置如下:
- from django.urls import path,include
-
- urlpatterns = [
- # path('admin/', admin.site.urls),
- path('api/', include('你的应用的名字.urls'))
- ]
第六步:创建数据库表
在应用文件夹下,找到并打开models.py
定义class类,每个类对应一张数据库表
- class Devices(models.Model):
- dev_code = models.CharField(max_length=24)
- dev_name = models.CharField(max_length=50)
- address = models.CharField(max_length=100)
- status = models.BooleanField()
-
-
- class Records(models.Model):
- dev = models.ForeignKey(to=Devices,on_delete=models.CASCADE)
- duration = models.IntegerField(default=0)
- amount = models.DecimalField(max_digits=10, decimal_places=2)
- create_time = models.DateTimeField(auto_created=True)
运行(数据迁移,创建表)
1)python manage.py makemigrations
2)python manage.py migrate
第七步:编写数据接口
在应用文件夹下,找到并打开views.py
定义class类,每个类就是一个接口,有get(查询)、post(添加)、put(修改)、delete(删除)
- from django.http import JsonResponse
- from django.views import View
- from api.models import *
- from datetime import datetime
- import math
- import json
-
- # Create your views here.
-
-
- class DevicesApi(View):
- def get(self, request):
- pagesize = 5
- result = Devices.objects.filter()
- params = request.GET
- keyword = params.get('key', '')
- page = params.get('page', '')
- sort = params.get('sort', '0')
- if(keyword != ''):
- result = result.filter(community_name__contains=keyword)
-
- if(sort == '1'):
- result = result.order_by('-id')
- elif(sort == '2'):
- result = result.order_by('id')
- records = result.count()
- print(page+'a')
- if(page != ''):
- page = int(page)
- start = (page - 1) * pagesize
- end = page * pagesize
- result = result[start:end]
-
- total = math.ceil(records / pagesize)
-
- data = []
- for item in result:
- data.append({
- 'id': item.id,
- 'dev_code': item.dev_code,
- 'community_name': item.community_name,
- 'dev_address': item.dev_address,
- 'dev_status': item.dev_status
- })
- return JsonResponse({'code': 200, 'data':data, 'total': total, 'page': page})
-
- def post(self,request):
- data = json.loads(request.body)
- # print(data)
- obj = Devices()
- obj.dev_code = data['dev_code']
- obj.community_name = data['community_name']
- obj.dev_address = data['dev_address']
- obj.dev_status = 0
- obj.save()
- return JsonResponse({'code': 200})
-
-
- class DevicesDel(View):
- def post(self, request):
- data = json.loads(request.body)
- # print(data)
- Devices.objects.filter(id__in=data).delete()
- return JsonResponse({'code': 200})
-
- class DevicesEdit(View):
- def get(self, request):
- devID = int(request.GET.get('id',0))
- if(devID>0):
- obj = Devices.objects.get(id=devID)
- if(obj.dev_status):
- obj.dev_status = 0
- else:
- obj.dev_status = 1
- obj.save()
- return JsonResponse({'code': 200})
-
- class DevicesInfo(View):
- def get(self, request):
- devID = int(request.GET.get('id', 0))
- result = {}
- if(devID > 0):
- obj = Devices.objects.get(id=devID)
- # print(obj)
- result = {'id': obj.id, 'dev_code': obj.dev_code, 'community_name': obj.community_name, 'dev_address': obj.dev_address, 'dev_status': obj.dev_status}
- return JsonResponse({'code': 200, 'data': result})
-
- class RecordApi(View):
- def post(self, request):
- data = json.loads(request.body)
- obj = Records()
- obj.dev_id_id = data['dev_id']
- obj.use_times = data['use_times']
- obj.amount = data['amount']
- obj.create_time = datetime.now()
- obj.save()
- return JsonResponse({'code': 200})
- def get(self, request):
- pagesize = 5
- result = Records.objects.filter().order_by('-id')
- params = request.GET
- page = params.get('page', '')
- records = result.count()
- if (page != ''):
- page = int(page)
- start = (page - 1) * pagesize
- end = page * pagesize
- result = result[start:end]
-
- total = math.ceil(records / pagesize)
- data = []
- for item in result:
- data.append({
- 'id': item.id,
- 'dev_code': item.dev_id.dev_code,
- 'community_name': item.dev_id.community_name,
- 'dev_address': item.dev_id.dev_address,
- 'dev_status': item.dev_id.dev_status,
- 'use_times': item.use_times,
- 'amount': item.amount,
- 'dev_id': item.dev_id_id
- })
- return JsonResponse({'code': 200, 'data': data, 'total': total, 'page': page})
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。