创建项目
pip install django
pip install djangorestframework
django-admin startproject mytool
cd mytool
python manage.py startapp idcs
idcs/models.py
from django.db import models
# Create your models here.
class Idc(models.Model):
name = models.CharField("机房名称",max_length=32)
address = models.CharField("机房地址",max_length=256)
phone = models.CharField("联系人",max_length=15)
email = models.EmailField("邮件地址",default="null")
latter = models.CharField("IDC简称",max_length=5)
def __str__(self):
return self.name
class Mate:
db_table = 'resources_idc'
idcs/views.py
from django.shortcuts import render
from .serializers import IdcSerializer
from rest_framework import viewsets
from idcs import models
class IdcsViewsets(viewsets.ModelViewSet):
"""
retrieve:
返回指定idc信息
list:
返回idc列表
destroy:
删除idc
update:
更新idc
create:
创建idc记录
"""
queryset = models.Idc.objects.all()
serializer_class = IdcSerializer
idcs/serializers.py
#!/usr/bin/env python
# encoding: utf-8
from rest_framework import serializers
from idcs import models
class IdcSerializer(serializers.Serializer):
'''
用户序列化类
'''
id = serializers.IntegerField(read_only=True)
name = serializers.CharField(required=True,
max_length=32,
label="机房名称",
help_text="请输入机房名称",
error_messages={"blank":"机房名称不能为空",
"required":"这个字段为必要字段"})
address = serializers.CharField(required=True,
max_length=256,
label="机房地址",
help_text="请输入机房名称",
error_messages={"blank":"机房地址不能为空",
"required":"这个字段为必要字段"})
phone = serializers.CharField(required=True,
max_length=15,
label="联系电话",
help_text="请输入联系电话",
error_messages={"blank":"联系电话不能为空",
"required":"这个字段为必要字段"})
email = serializers.EmailField(required=True,
label="联系邮件",
help_text="请输入联系邮件",
error_messages={"blank":"联系邮件不能为空",
"required":"这个字段为联系邮件"})
latter = serializers.CharField(required=True,
max_length=5,
label="机房简称",
help_text="请输入机房的简称",
error_messages={"blank":"机房简称不能为空",
"required":"这个字段为机房简称"})
def create(self, validated_data):
return models.Idc.objects.create(**validated_data)
def update(self, instance, validated_data):
instance.name = validated_data.get("name",instance.name)
instance.address = validated_data.get("address",instance.address)
instance.phone = validated_data.get("phone",instance.phone)
instance.email = validated_data.get("name",instance.email)
instance.latter = validated_data.get("name",instance.latter)
return instance
mytool/urls.py
"""mytool URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import include
from django.urls import path
from django.urls import re_path
from rest_framework import routers
from users.views import UserViewsets
from idcs.views import IdcsViewsets
router = routers.DefaultRouter()
router.register(r"users",viewset=UserViewsets,basename="users")
#注册路由idcs
router.register(r"idcs",viewset=IdcsViewsets,basename="idcs")
urlpatterns = [
re_path(r'^', include(router.urls)),
path('admin/', admin.site.urls),
]
mytool/setting.py
INSTALLED_APPS = [
...
'rest_framework',
'idcs',
]
#查询,获取机房全部数据list
request = requests.get("http://60.1.1.28:8888/idcs/")
print(request.text)
[{"id":1,"name":"兆维","address":"朝阳","phone":"13812345678","email":"xxx@zw.com","latter":""},{"id":2,"name":"歌华","address":"昌平","phone":"2222","email":"cp@zw.com","latter":""},{"id":3,"name":"华为","address":"","phone":"","email":"null","latter":""},{"id":4,"name":"华为1","address":"西城区","phone":"123","email":"4541@qaq.com","latter":"hw"},{"id":8,"name":"A机房","address":"动车","phone":"123","email":"121@qq.com","latter":"3"}]
#查询,获取单个机房信息
request0 = requests.get("http://60.1.1.28:8888/idcs/1")
print(request0.text)
{"id":1,"name":"兆维","address":"朝阳","phone":"13812345678","email":"xxx@zw.com","latter":""}
#POST,新建一个机房记录
headers = {'Content-Type': 'application/json'}
data={
"name": "A机房",
"address": "动车",
"phone": "123",
"email": "121@qq.com",
"latter": "3",
}
request1 = requests.post("http://60.1.1.28:8888/idcs/",data=data)
print(request1.text)
{"id":9,"name":"A机房","address":"动车","phone":"123","email":"121@qq.com","latter":"3"}
#根据id删除一个机房信息
request2 = requests.delete("http://60.1.1.28:8888/idcs/7")
print(request2.text,request2.status_code)
#根据id修改机房信息
data1={
"id": "9",
"name": "B机房",
"address": "lfdjslkfjldsj",
"phone": "123456",
"email": "121@qq.com",
"latter": "3",
}
headers = {'Content-Type': 'application/json'}
request3 = requests.put("http://60.1.1.28:8888/idcs/9/",headers=headers,data=json.dumps(data1))
print(request3.text)
{"id":9,"name":"B机房","address":"lfdjslkfjldsj","phone":"123456","email":"B机房","latter":"B机房"}
添加网页api接口文档
mytool/urls.py
#新增
from rest_framework.documentation import include_docs_urls
urlpatterns = [
re_path(r'^', include(router.urls)),
re_path(r'^doc/',include_docs_urls(title="接口文档")),
path('admin/', admin.site.urls),
]
然后访问http://60.1.1.28:8888/doc/会报错,需要安装coreapi
pip install coreapi
再次访问http://60.1.1.28:8888/doc/还是报错AttributeError: ‘AutoSchema’ object has no attribute ‘get_link’
mytool/setting.py新增
#新增
REST_FRAMEWORK = {
'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema'
}
再次访问http://60.1.1.28:8888/doc/,就没问题了.