Django-3

 Django-3

 

一、创建数据库
mysql> CREATE DATABASE `devops` /*!40100 DEFAULT CHARACTER SET utf8 */;
Query OK, 1 row affected (0.01 sec)

创建不同版本的django
https://www.zhangshengrong.com/p/w4N7B05jar/


Django 1.11
启动报错:https://www.cnblogs.com/yanlin-10/p/9714793.html

安装pip install mysqlclient

版本控制列表:

backcall==0.1.0
certifi==2018.4.16
chardet==3.0.4
click==6.7
coreapi==2.3.3
coreapi-cli==1.0.9
coreschema==0.0.4
decorator==4.3.0
Django==1.11.13
djangorestframework==3.8.2
httpie==0.9.9
idna==2.6
ipython==6.4.0
ipython-genutils==0.2.0
itypes==1.1.0
jedi==0.12.0
Jinja2==2.10
MarkupSafe==1.0
mysqlclient==1.3.12
parso==0.2.0
pexpect==4.5.0
pickleshare==0.7.4
prompt-toolkit==1.0.15
ptyprocess==0.5.2
Pygments==2.2.0
pytz==2018.4
requests==2.18.4
simplegeneric==0.8.1
six==1.11.0
traitlets==4.3.2
uritemplate==3.0.0
urllib3==1.22
wcwidth==0.1.7
View Code

 

 

(venv) D:\PycharmProjects\myenv\ops>python manage.py showmigrations
admin
[ ] 0001_initial
[ ] 0002_logentry_remove_auto_add
auth
[ ] 0001_initial
[ ] 0002_alter_permission_name_max_length
[ ] 0003_alter_user_email_max_length
[ ] 0004_alter_user_username_opts
[ ] 0005_alter_user_last_login_null
[ ] 0006_require_contenttypes_0002
[ ] 0007_alter_validators_add_error_messages
[ ] 0008_alter_user_username_max_length
contenttypes
[ ] 0001_initial
[ ] 0002_remove_content_type_name
idcs
(no migrations)
sessions
[ ] 0001_initial

(venv) D:\PycharmProjects\myenv\ops>python manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
Applying admin.0002_logentry_remove_auto_add... OK
Applying contenttypes.0002_remove_content_type_name... OK
Applying auth.0002_alter_permission_name_max_length... OK
Applying auth.0003_alter_user_email_max_length... OK
Applying auth.0004_alter_user_username_opts... OK
Applying auth.0005_alter_user_last_login_null... OK
Applying auth.0006_require_contenttypes_0002... OK
Applying auth.0007_alter_validators_add_error_messages... OK
Applying auth.0008_alter_user_username_max_length... OK
Applying sessions.0001_initial... OK

(venv) D:\PycharmProjects\myenv\ops>python manage.py showmigrations
admin
[X] 0001_initial
[X] 0002_logentry_remove_auto_add
auth
[X] 0001_initial
[X] 0002_alter_permission_name_max_length
[X] 0003_alter_user_email_max_length
[X] 0004_alter_user_username_opts
[X] 0005_alter_user_last_login_null
[X] 0006_require_contenttypes_0002
[X] 0007_alter_validators_add_error_messages
[X] 0008_alter_user_username_max_length
contenttypes
[X] 0001_initial
[X] 0002_remove_content_type_name
idcs
(no migrations)
sessions
[X] 0001_initial

(venv) D:\PycharmProjects\myenv\ops>python manage.py makemigrations idcs
Migrations for 'idcs':
apps\idcs\migrations\0001_initial.py
- Create model Idc

(venv) D:\PycharmProjects\myenv\ops>python manage.py showmigrations
admin
[X] 0001_initial
[X] 0002_logentry_remove_auto_add
auth
[X] 0001_initial
[X] 0002_alter_permission_name_max_length
[X] 0003_alter_user_email_max_length
[X] 0004_alter_user_username_opts
[X] 0005_alter_user_last_login_null
[X] 0006_require_contenttypes_0002
[X] 0007_alter_validators_add_error_messages
[X] 0008_alter_user_username_max_length
contenttypes
[X] 0001_initial
[X] 0002_remove_content_type_name
idcs
[ ] 0001_initial
sessions
[X] 0001_initial

同步好表结构:

(venv) D:\PycharmProjects\myenv\ops>python manage.py migrate idcs
Operations to perform:
Apply all migrations: idcs
Running migrations:
Applying idcs.0001_initial... OK

(venv) D:\PycharmProjects\myenv\ops>
同步好表结构

怎样序列化模型

1,模型添加两条数据
(venv) D:\PycharmProjects\myenv\ops>python manage.py shell
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)

>>> from idcs.models import Idc
>>> idc = Idc()
>>> idc.name = "子镇机房"
>>> idc.address = "山西子镇机房"
>>> idc.phone = "12345678"
>>> idc.email = "weizi@163.com"
>>> idc.letter = "zz"
>>> idc.save()
>>>
>>> idc.id = None
>>> idc.name = "潞城机房"
>>> idc.address = "山西潞城机房"
>>> idc.letter = "lc"
>>> idc.save()
>>>
>>> Idc.objects.all()
<QuerySet [<Idc: 子镇机房>, <Idc: 潞城机房>]>
>>>
>>> from idcs.serializers import IdcSerializer
>>> idc = Idc.objects.get(pk=1)
>>> idc
<Idc: 子镇机房>
>>>
>>> serializer = IdcSerializer(idc)
>>> serializer
IdcSerializer(<Idc: 子镇机房>):
id = IntegerField()
name = CharField()
address = CharField()
phone = CharField()
email = EmailField()
letter = CharField()

>>> serializer.data
{'id': 1, 'name': '子镇机房', 'address': '山西子镇机房', 'phone': '12345678', 'email': 'weizi@163.com', 'letter': 'zz'}
>>>
>>> type(a)
<class 'rest_framework.utils.serializer_helpers.ReturnDict'>
不建议用
>>> import json
>>> json.dumps(serializer.data)
'{"id": 1, "name": "\\u5b50\\u9547\\u673a\\u623f", "address": "\\u5c71\\u897f\\u5b50\\u9547\\u673a\\u623f", "phone": "12345678", "
email": "weizi@163.com", "letter": "zz"}'

建议使用

>>> from rest_framework.renderers import JSONRenderer
>>> help(JSONRenderer)
Help on class JSONRenderer in module rest_framework.renderers:

class JSONRenderer(BaseRenderer)
| Renderer which serializes to JSON.
|
| Method resolution order:
| JSONRenderer
| BaseRenderer
| builtins.object
|
| Methods defined here:
|
| get_indent(self, accepted_media_type, renderer_context)
|
| render(self, data, accepted_media_type=None, renderer_context=None)
| Render `data` into JSON, returning a bytestring.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| charset = None
|
| compact = True
|
| encoder_class = <class 'rest_framework.utils.encoders.JSONEncoder'>
| JSONEncoder subclass that knows how to encode date/time/timedelta,
| decimal types, generators and other basic python objects.
|
| ensure_ascii = False
|
| format = 'json'

>>>
>>> jr = JSONRenderer()
>>> jr.render(serializer.data) #返回前端的json数据
b'{"id":1,"name":"\xe5\xad\x90\xe9\x95\x87\xe6\x9c\xba\xe6\x88\xbf","address":"\xe5\xb1\xb1\xe8\xa5\xbf\xe5\xad\x90\xe9\x95\x87\xe
6\x9c\xba\xe6\x88\xbf","phone":"12345678","email":"weizi@163.com","letter":"zz"}'
>>>
用httpresponse对象返回,

 

获取数据步骤:
1,mysql
2,queryset = Idc.objects.all()
3,json.dumps() ===》 序列化
4,HttpResponse()

 

反序列化,

类型是BytesIO
假设浏览器写数据到服务器
>>> content
b'{"id":1,"name":"\xe5\xad\x90\xe9\x95\x87\xe6\x9c\xba\xe6\x88\xbf","address":"\xe5\xb1\xb1\xe8\xa5\xbf\xe5\xad\x90\xe9\x95\x87\xe
6\x9c\xba\xe6\x88\xbf","phone":"12345678","email":"weizi@163.com","letter":"zz"}'
>>>
>>> from django.utils.six import BytesIO
>>> stream = BytesIO(content)
>>> stream
<_io.BytesIO object at 0x0000000004341518>
>>>

>>> dir(stream)
['__class__', '__del__', '__delattr__', '__dict__', '__dir__', '__doc__', '__enter__', '__eq__', '__exit__', '__format__', '__ge__
', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__lt__', '__n
e__', '__new__', '__next__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__', '__sizeof__', '__str__', '_
_subclasshook__', '_checkClosed', '_checkReadable', '_checkSeekable', '_checkWritable', 'close', 'closed', 'detach', 'fileno', 'fl
ush', 'getbuffer', 'getvalue', 'isatty', 'read', 'read1', 'readable', 'readinto', 'readinto1', 'readline', 'readlines', 'seek', 's
eekable', 'tell', 'truncate', 'writable', 'write', 'writelines']
>>> stream.read()
b'{"id":1,"name":"\xe5\xad\x90\xe9\x95\x87\xe6\x9c\xba\xe6\x88\xbf","address":"\xe5\xb1\xb1\xe8\xa5\xbf\xe5\xad\x90\xe9\x95\x87\xe
6\x9c\xba\xe6\x88\xbf","phone":"12345678","email":"weizi@163.com","letter":"zz"}'
>>>
>>> from rest_framework.parsers import JSONParser
>>> from rest_framework.parsers import JSONParser
>>>
>>>
>>> content
b'{"id":1,"name":"\xe5\xad\x90\xe9\x95\x87\xe6\x9c\xba\xe6\x88\xbf","address":"\xe5\xb1\xb1\xe8\xa5\xbf\xe5\xad\x90\xe9\x95\x87\xe
6\x9c\xba\xe6\x88\xbf","phone":"12345678","email":"weizi@163.com","letter":"zz"}'
>>> stream = BytesIO(content)
>>> data = JSONParser().parse(stream)
>>> data #标准的JSON格式
{'id': 1, 'name': '子镇机房', 'address': '山西子镇机房', 'phone': '12345678', 'email': 'weizi@163.com', 'letter': 'zz'}
>>> type(data)
<class 'dict'>
>>>
>>> serializer = IdcSerializer(data=data)
>>> serializer
IdcSerializer(data={'id': 1, 'name': '子镇机房', 'address': '山西子镇机房', 'phone': '12345678', 'email': 'weizi@163.com', 'letter
': 'zz'}):
id = IntegerField()
name = CharField()
address = CharField()
phone = CharField()
email = EmailField()
letter = CharField() #规则未生效退出重新搞
>>>
(venv) D:\PycharmProjects\myenv\ops>python manage.py shell
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from idcs.serializers import IdcSerializer
>>> data = {'id': 1, 'name': '子镇机房', 'address': '山西子镇机房', 'phone': '12345678', 'email': 'weizi@163.com', 'letter': 'zz'}

>>> serializer = IdcSeralizer(data=data)
Traceback (most recent call last):
File "<console>", line 1, in <module>
NameError: name 'IdcSeralizer' is not defined
>>> serializer = IdcSerializer(data=data)
>>> serializer
IdcSerializer(data={'id': 1, 'name': '子镇机房', 'address': '山西子镇机房', 'phone': '12345678', 'email': 'weizi@163.com', 'letter
': 'zz'}):
id = IntegerField(read_only=True)
name = CharField(max_length=32, required=True)
address = CharField(max_length=256, required=True)
phone = CharField(max_length=15, required=True)
email = EmailField(required=True)
letter = CharField(max_length=5, required=True) #规则生效
>>>


验证成功返回True
>>> serializer.is_valid()
True


拿到干净的数据
>>> serializer.validated_data
OrderedDict([('name', '子镇机房'), ('address', '山西子镇机房'), ('phone', '12345678'), ('email', 'weizi@163.com'), ('letter', 'zz'
)])

做操作

Serializers.py
classIdcSerializer(serializers.Serializer):
  """
  Idc序列化类
  """
  id=serializers.IntegerField(read_only=True)
  name=serializers.CharField(required=True,max_length=32)
  address=serializers.CharField(required=True,max_length=256)
  phone=serializers.CharField(required=True,max_length=15)
  email=serializers.EmailField(required=True)
  letter=serializers.CharField(required=True,max_length=5)

  defcreate(self,validated_data):
  returnIdc.objects.create(**validated_data)


(venv) D:\PycharmProjects\myenv\ops>python manage.py shell
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from idcs.serializers import IdcSerializer
>>> data = {'id': 1, 'name': '子镇机房', 'address': '山西子镇机房', 'phone': '12345678', 'email': 'weizi@163.com', 'letter': 'zz'}

>>> del data['id']
>>> data
{'name': '子镇机房', 'address': '山西子镇机房', 'phone': '12345678', 'email': 'weizi@163.com', 'letter': 'zz'}
>>> serializer = IdcSerializer(data=data)
>>> serializer.is_valid()
True
>>> serializer.save()
<Idc: 子镇机房>
>>>
>>> from idcs.models import Idc
>>> Idc.objects.all()
<QuerySet [<Idc: 子镇机房>, <Idc: 潞城机房>, <Idc: 子镇机房>, <Idc: 子镇机房>, <Idc: 子镇机房>]>
>>> data = IdcSerializer(Idc.objects.all(), many=True)
>>> data
IdcSerializer(<QuerySet [<Idc: 子镇机房>, <Idc: 潞城机房>, <Idc: 子镇机房>, <Idc: 子镇机房>, <Idc: 子镇机房>]>, many=True):
id = IntegerField(read_only=True)
name = CharField(max_length=32, required=True)
address = CharField(max_length=256, required=True)
phone = CharField(max_length=15, required=True)
email = EmailField(required=True)
letter = CharField(max_length=5, required=True)
>>> from rest_framework.renderers import JSONRenderer
>>> content = JSONRenderer().render(data.data)
>>> content
b'[{"id":1,"name":"\xe5\xad\x90\xe9\x95\x87\xe6\x9c\xba\xe6\x88\xbf","address":"\xe5\xb1\xb1\xe8\xa5\xbf\xe5\xad\x90\xe9\x95\x87\x
e6\x9c\xba\xe6\x88\xbf","phone":"12345678","email":"weizi@163.com","letter":"zz"},{"id":2,"name":"\xe6\xbd\x9e\xe5\x9f\x8e\xe6\x9c
\xba\xe6\x88\xbf","address":"\xe5\xb1\xb1\xe8\xa5\xbf\xe6\xbd\x9e\xe5\x9f\x8e\xe6\x9c\xba\xe6\x88\xbf","phone":"12345678","email":
"weizi@163.com","letter":"lc"},{"id":3,"name":"\xe5\xad\x90\xe9\x95\x87\xe6\x9c\xba\xe6\x88\xbf","address":"\xe5\xb1\xb1\xe8\xa5\x
bf\xe5\xad\x90\xe9\x95\x87\xe6\x9c\xba\xe6\x88\xbf","phone":"12345678","email":"weizi@163.com","letter":"zz"},{"id":4,"name":"\xe5
\xad\x90\xe9\x95\x87\xe6\x9c\xba\xe6\x88\xbf","address":"\xe5\xb1\xb1\xe8\xa5\xbf\xe5\xad\x90\xe9\x95\x87\xe6\x9c\xba\xe6\x88\xbf"
,"phone":"12345678","email":"weizi@163.com","letter":"zz"},{"id":5,"name":"\xe5\xad\x90\xe9\x95\x87\xe6\x9c\xba\xe6\x88\xbf","addr
ess":"\xe5\xb1\xb1\xe8\xa5\xbf\xe5\xad\x90\xe9\x95\x87\xe6\x9c\xba\xe6\x88\xbf","phone":"12345678","email":"weizi@163.com","letter
":"zz"}]'
>>>

1,序列化
  1 )拿到queryset
  2)将queryset给序列化类
    Serializer = IdcSerializer(idc)
    多个对象 serializer = IdcSerializer(quueeryset, many=Tr)

  3)转JSON格式
  JSONRenderer().render(serializer.data)

2,反序列化
  Data = JSONParser().Parse(BytesIO(content))
  serializer =IdcSerializer(data=data)
  serializer .is_valid()
  Serializer.save()

 

def idc_list():
  get:
  返回所有记录
  post:
  创建一条记录

def idc_detail(pk):
  get:
  返回指定记录
  put:
  修改指定记录
  delete;
  删除这条记录


方法1

安装httpie
(venv) D:\PycharmProjects\myenv\ops>pip install httpie
Collecting httpie
Downloading https://files.pythonhosted.org/packages/d7/46/cfb014b9de6ac5cdd1fa06d85f411dd9506102c8b094906460b4a1710681/httpie-1.
0.2-py2.py3-none-any.whl (59kB)
100% |████████████████████████████████| 61kB 93kB/s
Requirement already satisfied: requests>=2.18.4 in c:\users\hbbn\appdata\local\programs\python\python37\lib\site-packages (from ht
tpie) (2.22.0)
Collecting colorama>=0.2.4; sys_platform == "win32" (from httpie)
Downloading https://files.pythonhosted.org/packages/4f/a6/728666f39bfff1719fc94c481890b2106837da9318031f71a8424b662e12/colorama-
0.4.1-py2.py3-none-any.whl
Collecting Pygments>=2.1.3 (from httpie)
Downloading https://files.pythonhosted.org/packages/5c/73/1dfa428150e3ccb0fa3e68db406e5be48698f2a979ccbcec795f28f44048/Pygments-
2.4.2-py2.py3-none-any.whl (883kB)
100% |████████████████████████████████| 890kB 216kB/s
Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in c:\users\hbbn\appdata\local\programs\python\python37\lib
\site-packages (from requests>=2.18.4->httpie) (1.25.3)
Requirement already satisfied: idna<2.9,>=2.5 in c:\users\hbbn\appdata\local\programs\python\python37\lib\site-packages (from requ
ests>=2.18.4->httpie) (2.8)
Requirement already satisfied: certifi>=2017.4.17 in c:\users\hbbn\appdata\local\programs\python\python37\lib\site-packages (from
requests>=2.18.4->httpie) (2019.6.16)
Requirement already satisfied: chardet<3.1.0,>=3.0.2 in c:\users\hbbn\appdata\local\programs\python\python37\lib\site-packages (fr
om requests>=2.18.4->httpie) (3.0.4)
Installing collected packages: colorama, Pygments, httpie
Successfully installed Pygments-2.4.2 colorama-0.4.1 httpie-1.0.2

(venv) D:\PycharmProjects\myenv\ops>python manage.py runserver 0.0.0.0:8000
Performing system checks...

System check identified no issues (0 silenced).
July 28, 2019 - 17:05:38
Django version 1.11, using settings 'ops.settings'
Starting development server at http://0.0.0.0:8000/
Quit the server with CTRL-BREAK.
Forbidden (CSRF cookie not set.): /idcs/
[28/Jul/2019 17:06:53] "POST /idcs/ HTTP/1.1" 403 2829

验证:

(venv) D:\PycharmProjects\myenv\ops>http --json POST http://127.0.0.1:8000/idcs/ aaa=bbb bbb=ccc
HTTP/1.0 403 Forbidden
Content-Length: 2829
Content-Type: text/html
Date: Sun, 28 Jul 2019 09:06:53 GMT
Server: WSGIServer/0.2 CPython/3.7.3
X-Frame-Options: SAMEORIGIN

<!DOCTYPE html>
#

方法2:postman

 

测试
(venv) D:\PycharmProjects\myenv\ops>http http://127.0.0.1:8000/idcs/1/
HTTP/1.0 200 OK
Content-Length: 118
Content-Type: application/json
Date: Sun, 28 Jul 2019 13:27:01 GMT
Server: WSGIServer/0.2 CPython/3.7.3
X-Frame-Options: SAMEORIGIN

{
  "address": "山西子镇机房",
  "email": "weizi@163.com",
  "id": 1,
  "letter": "zz",
  "name": "子镇机房",
  "phone": "12345678"
}

版本django1.11代码

1,views.py

from django.shortcuts import render
from django.http import HttpResponse
from .models import Idc
from .serializers import IdcSerializer
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser

# Create your views here.
#####################版本一########################
class JSONResponse(HttpResponse):
    def __init__(self, data, **kwargs):
        kwargs.setdefault('content_type', 'application/json')
        content = JSONRenderer().render(data)
        super(JSONResponse, self).__init__(content=content, **kwargs)
        # HttpResponse(content)

def idc_list(request, *args, **kwargs):
    if request.method == "GET":
        queryset = Idc.objects.all()
        serializer = IdcSerializer(queryset,many=True)

        return JSONResponse(serializer.data)
        # content = JSONRenderer().render(serializer.data)
        # return HttpResponse(content, content_type="application/json")

    elif request.method == "POST":
        content = JSONParser().parse(request)
        serializer = IdcSerializer(data=content)
        if serializer.is_valid():
            serializer.save()
            content = JSONRenderer().render(serializer.data)
            return HttpResponse(content, content_type="application/json")

def idc_detail(request, pk, *args, **kwargs):
    try:
        idc = Idc.objects.get(pk=pk)
    except Idc.DoesNotExist:
        return HttpResponse(status=404)

    if request.method == "GET":
        serializer = IdcSerializer(idc)
        return JSONResponse(serializer.data)
    elif request.method == "PUT":
        content = JSONParser().parse(request)
        serializer = IdcSerializer(idc, data=content)
        if serializer.is_valid():
            serializer.save()
            return JSONResponse(serializer.data)
        return JSONResponse(serializer.errors, status=400)

    elif request.method == "DELETE":
        idc.delete()
        return HttpResponse(status=204)

############################ 版本二 #################################
from rest_framework.decorators import api_view
from rest_framework import status
from rest_framework.response import Response

@api_view(["GET", "POST"])
def idc_list_v2(request, format=None, *args, **kwargs):
    if request.method == "GET":
        queryset = Idc.objects.all()  #先拿到数据
        serializer = IdcSerializer(queryset, many=True)  #序列化
        # return JSONResponse(serializer.data) #序列化内容转化成json格式的字符串
        return Response(serializer.data)
    elif request.method == "POST":
        print(request.data)
        serializer = IdcSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
        #     return JSONResponse(serializer.data, status.HTTP_201_CREATED)
        # return JSONResponse(serializer.data, status.HTTP_400_BAD_REQUEST)
            return Response(serializer.data, status.HTTP_201_CREATED)
        return Response(serializer.data, status.HTTP_400_BAD_REQUEST)

@api_view(["GET", "PUT", "DELETE"])
def idc_detail_v2(request, pk,format=None, *args, **kwargs):
    try:
        idc = Idc.objects.get(pk=pk)
    except Idc.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)

    if request.method == "GET":
        serializer = IdcSerializer(idc) #序列化
        return Response(serializer.data)
    elif request.method == "PUT":
        serializer = IdcSerializer(idc,data=request.data) #idc序列化#提交过来的数据全部放request.data里了
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
    elif request.method == "DELETE":
        idc.delete()
        return HttpResponse(status=status.HTTP_204_NO_CONTENT)

from rest_framework.reverse import reverse
@api_view(["GET"])
def api_root(request, format=None,*args, **kwargs):
    return Response({
        "idcs":reverse("idc-list",request=request,format=format)
    })

############################ 版本三 #################################
from rest_framework.views import APIView
from django.http import Http404

class IdcList(APIView):
    def get(self,request, format=None):
        queryset = Idc.objects.all()
        serializer = IdcSerializer(queryset, many=True)
        return Response(serializer.data)

    def post(self, request, format=None):
        serializer = IdcSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.data, status=status.HTTP_400_BAD_REQUEST)

class IdcDetail(APIView):

    def get_object(self, pk):
        try:
            return Idc.objects.get(pk=pk)
        except Idc.DoesNotExist:
            raise Http404

    def get(self, request, pk, format=None):
        idc = self.get_object(pk)
        serializer = IdcSerializer(idc)
        return Response(serializer.data)

    def put(self, request, pk, format=None):
        idc = self.get_object(pk)
        serializer = IdcSerializer(idc,data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_404_NOT_FOUND)

    def delete(self, request, pk, format=None):
        idc = self.get_object(pk)
        idc.delete()
        return HttpResponse(status=status.HTTP_204_NO_CONTENT)

############################ 版本四 #################################
from rest_framework import mixins, generics

class IdcList_v4(generics.GenericAPIView,
                 mixins.ListModelMixin,
                 mixins.CreateModelMixin):

    queryset = Idc.objects.all()
    serializer_class = IdcSerializer

    def get(self,request, *args, **kwargs):
        return self.list(request, *args, **kwargs)

    def post(self, request, *args, **kwargs):
        return self.create(request, *args, **kwargs)

class IdcDetail_v4(generics.GenericAPIView,
                   mixins.RetrieveModelMixin,
                   mixins.UpdateModelMixin,
                   mixins.DestroyModelMixin):
    queryset = Idc.objects.all()
    serializer_class = IdcSerializer

    def get(self, request, *args, **kwargs):
        return self.retrieve(request, *args, **kwargs)

    def put(self, request, *args, **kwargs):
        return self.update(request, *args, **kwargs)

    def delete(self, request,*args, **kwargs):
        return self.destroy(request, *args, **kwargs)

############################ 版本五 #################################

class IdcList_v5(generics.ListCreateAPIView):
    queryset = Idc.objects.all()
    serializer_class = IdcSerializer

class IdcDetail_v5(generics.RetrieveUpdateDestroyAPIView):
    queryset = Idc.objects.all()
    serializer_class = IdcSerializer

############################ 版本六 #################################
from rest_framework import viewsets
from rest_framework import mixins, generics

class IdcListViewset(viewsets.GenericViewSet,
                     mixins.ListModelMixin,
                     mixins.RetrieveModelMixin,
                     mixins.DestroyModelMixin,
                     mixins.UpdateModelMixin,
                     mixins.CreateModelMixin):
    queryset = Idc.objects.all()
    serializer_class = IdcSerializer

############################ 版本七 #################################

class IdcListViewset_v7(viewsets.ModelViewSet):
    queryset = Idc.objects.all()
    serializer_class = IdcSerializer
View Code

 

2,urls.py 

from django.conf.urls import url, include
from .views import idc_list, idc_detail


########################版本一############################
urlpatterns = [
    url('^idcs/$', idc_list),
    url('^idcs/(?P<pk>[0-9]+)/$', idc_detail),
]
########################版本二############################
from . import views
from rest_framework.urlpatterns import format_suffix_patterns

urlpatterns = [
    url("^$", views.api_root),
    url('^idcs/$', views.idc_list_v2, name="idc-list"),
    url('^idcs/(?P<pk>[0-9]+)/$', views.idc_detail_v2, name="idc-detail"),
]
#给网址添加可选的格式后缀
urlpatterns = format_suffix_patterns(urlpatterns)


########################版本三############################
urlpatterns = [
    url("^$", views.api_root),
    url("^idcs/$", views.IdcList.as_view(), name="idc-list"),
    url('^idcs/(?P<pk>[0-9]+)/$', views.IdcDetail.as_view(), name="idc-detail"),
]
urlpatterns = format_suffix_patterns(urlpatterns)

########################版本四############################
urlpatterns = [
    url("^$", views.api_root),
    url("^idcs/$", views.IdcList_v4.as_view(), name="idc-list"),
    url('^idcs/(?P<pk>[0-9]+)/$', views.IdcDetail_v4.as_view(), name="idc-detail"),
]
urlpatterns = format_suffix_patterns(urlpatterns)
########################版本五############################
urlpatterns = [
    url("^$", views.api_root),
    url("^idcs/$", views.IdcList_v5.as_view(), name="idc-list"),
    url('^idcs/(?P<pk>[0-9]+)/$', views.IdcDetail_v5.as_view(), name="idc-detail"),
]
urlpatterns = format_suffix_patterns(urlpatterns)
########################版本六############################
idc_list = views.IdcListViewset.as_view({
    "get": "list",
    "post": "create"
})

idc_detail = views.IdcListViewset.as_view({
    "get":"retrieve",
    "put":"update",
    "delete":"destroy"
})


urlpatterns = [
    url("^$", views.api_root),
    url("^idcs/$", idc_list, name="idc-list"),
    url('^idcs/(?P<pk>[0-9]+)/$', idc_detail, name="idc-detail"),
]
########################版本七############################
from rest_framework.routers import DefaultRouter

route = DefaultRouter()
route.register("idcs", views.IdcListViewset_v7)
urlpatterns= [
    url(r'^', include(route.urls)),
]
View Code

 

3,serializer.py

from rest_framework import serializers

from .models import Idc


class IdcSerializer(serializers.Serializer):
    """
    Idc 序列化类
    """
    id      = serializers.IntegerField(read_only=True)
    name    = serializers.CharField(required=True, max_length=32)
    address = serializers.CharField(required=True, max_length=256)
    phone   = serializers.CharField(required=True, max_length=15)
    email   = serializers.EmailField(required=True)
    letter  = serializers.CharField(required=True, max_length=5)

    def create(self, validated_data):
        return 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("email", instance.email)
        instance.save()
        return instance
View Code

 

4,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("机房联系email")
    letter  = models.CharField("idc 字母简称",max_length=5)

    def __str__(self):
        return self.name

    class Meta:
        db_table = 'resources_idc'
View Code

 

5,settings.py

"""
Django settings for ops project.

Generated by 'django-admin startproject' using Django 1.11.

For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""

import os
import sys
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, os.path.join(BASE_DIR, 'apps'))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'ekig$sdv7kiwg5*hy@1necs$uyo6fl8nbs5*^m6g6+!(j#yzf@'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ['*']


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'idcs.apps.IdcsConfig',
]

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',
]

ROOT_URLCONF = 'ops.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'ops.wsgi.application'


# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases

DATABASES = {
    # 'default': {
    #     'ENGINE': 'django.db.backends.sqlite3',
    #     'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    # }
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'USER': 'root',
        'PASSWORD': 'XXXXX',
        'NAME': 'devops1',
        'PORT': 3306,
        'HOST': '192.168.245.128',
        'OPTIONS': {
            'init_command': 'SET default_storage_engine=INNODB',
        },
    },
}


# Password validation
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/

LANGUAGE_CODE = 'zh-Hans'

TIME_ZONE = 'Asia/Shanghai'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/

STATIC_URL = '/static/'
View Code

 

6,urls.py

from django.conf.urls import url, include
from django.contrib import admin

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^', include('idcs.urls')),
]
View Code

 

django1.11 rest_framework.documentation + coreapi

链接:https://www.jianshu.com/p/b2fd03f2390c

 

queryset 介绍:

https://blog.csdn.net/youyou1543724847/article/details/85940565

 

posted on 2019-07-28 16:18  微子天明  阅读(362)  评论(0编辑  收藏  举报

导航