Django REST框架使用

参考网站:http://www.django-rest-framework.org/tutorial/1-serialization/

首先,需要安装django,djangorestframework,pygments等包。

安装方法

pip install django
pip install djangorestframework
pip install pygments

创建django项目

django-admin startproject RESTful

cd RESTful

python manage.py startapp snippets



在 RESTful/settings.py文件中添加

INSTALLED_APPS = [
    ...
    'rest_framework',
    'snippets',
]

编辑 ​​​​​​snippets/models.py文件

from django.db import models

class Snippet(models.Model):
    title = models.CharField(max_length=100,blank=True,default='')
    code = models.TextField()
    linenos = models.BooleanField(default=False)
    

此时,需要为我们的模型创建初始迁移,并同步数据库。

python manage.py makemigrations

python manage.py migrate

snippets的目录下创建一个文件serializers.py并编辑

from rest_framework import serializers
from snippets.models import Snippet

class SnippetSerializer(serializers.ModelSerializer):
    class Meta:
        model = Snippet
        fields = ('id','title','code','linenos')

进入Django shell

python manage.py shell

在shell中进行如下操作

>>>from snippets.models import Snippet
>>>from snippets.serializers import SnippetSerializer

>>>snippet = Snippet(code='哈哈')
>>>snippet.save()
>>>#我们往数据库里插入了一条数据,现在让我们序列化这个实例
>>>serializer = SnippetSerializer(snippet)
>>>serializer.data
{'id': 1, 'title': '', 'code': '哈哈', 'linenos': True}
>>>#现在让我们多插入几条数据
>>>snippet = Snippet(code='嘻嘻')
>>>snippet.save()
>>>snippet = Snippet(code='哼哼')
>>>snippet.save()
>>>#你也可以查看数据格式
>>>serializer1 = SnippetSerializer()
>>>print(str(serializer1))
SnippetSerializer():
    id = IntegerField(label='ID', read_only=True)
    title = CharField(allow_blank=True, max_length=100, required=False)
    code = CharField(style={'base_template': 'textarea.html'})
    linenos = BooleanField(required=False)
>>>#序列化操作
>>>from rest_framework.renderers import JSONRenderer
>>>from rest_framework.parsers import JSONParser
>>>content = JSONRenderer().render(serializer.data)
>>>content
b'{"id":1,"title":"","code":"\xe5\x93\x88\xe5\x93\x88","linenos":true}'
>>>#反序列化操作
>>>from django.utils.six import BytesIO
>>>stream = BytesIO(content)
>>>stream
<_io.BytesIO object at 0x7f3ff8bb8990>
>>>data = JSONParser().parse(stream)
>>>data
{'id': 1, 'title': '', 'code': '哈哈', 'linenos': True}
>>>#现在将原始数据类型还原为完全填充的对象实例
>>>serializer = SnippetSerializer(data=data)
>>>serializer.is_valid()
True
>>>serializer.validated_data
OrderedDict([('title', ''), ('code', '哈哈'), ('linenos', True)])
>>>#序列化查询集,只需many=True在序列化程序参数中添加一个标志
>>>serializer = SnippetSerializer(Snippet.objects.all(),many=True)
>>>serializer.data
[OrderedDict([('id', 1), ('title', ''), ('code', '哈哈'), ('linenos', True)]), OrderedDict([('id', 2), ('title', ''), ('code', '嘻嘻'), ('linenos', True)]), OrderedDict([('id', 3), ('title', ''), ('code', '哼哼'), ('linenos', True)]),]
>>>exit()

接下来使用Serializer编写常规Django视图

编辑snippets/views.py文件

from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser
from snippets.models import Snippet
from snippets.serializers import SnippetSerializer

@csrf_exempt
def snippet_list(request):
    
    #查询所有
    if request.method == 'GET':
        snippets = Snippet.objects.all()
        serializer = SnipperSerializer(snippets.many=True)
        return JsonResponse(serializer.data,safe=False)

    #添加
    elif request.method == 'POST':
        data = JSONParser().parse(request)
        serializer = SnippetSerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse(serializer.data,status=201)
        return JsonResponse(serializer.errors,status=400)


@csrf_exempt
def snippet_datail(request,pk):
    try:
        snippet = Snippet.objects.get(pk=pk)
    except Snippet.DoesNotExist:
        return HttpResponse(status=404)    

    #查询
    if request.method == 'GET':
        serializer = SnippetSerializer(snippet)
        return JsonResponse(serializer.data)

    #修改
    elif request.method == 'POST':
        data = JSONParser().parse(request)
        serializer = SnippetSerializer(snippet,data=data)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse(serializer.data)
        return JsonResponse(serializer.errors,status=400)

    #删除
    elif request.method == 'DELETE':
        snippet.dalete()
        return HttpResponse(status=204)


    

接下来连接这些视图,创建snippets/urls.py

from django.conf.urls import url
from snippets import views

urlpatterns = [
    url(r'snip/$',views.snippet_list),
    url(r'snip/(?P<pk>[0-9]+)/$',views.snippet_datail),
]

修改RESTful/urls.py文件,添加如下代码

from django.conf.urls import url,include

urlpatterns = [
    url(r'^',include('snippets,urls')),

]

最后,启动服务

python manage.py runserver 

在另一个终端窗口中来进行测试

我们利用httpie来测试我们的API,安装方法如下

pip install httpie

操作如下

(django_venv) j:~/pythonfile$ http http://127.0.0.1:8000/snip/
HTTP/1.0 200 OK
Content-Length: 260
Content-Type: application/json
Date: Fri, 10 Aug 2018 02:21:46 GMT
Server: WSGIServer/0.2 CPython/3.6.4
X-Frame-Options: SAMEORIGIN

[
    {
        "code": "哈哈",
        "id": 1,
        "linenos": true,
        "title": ""
    },
    {
        "code": "嘻嘻",
        "id": 2,
        "linenos": true,
        "title": ""
    },
    {
        "code": "哼哼",
        "id": 3,
        "linenos": true,
        "title": ""
    }
]

(django_venv) j:~/pythonfile$ http post http://127.0.0.1:8000/snip/ code="撒有哪啦"
HTTP/1.0 201 Created
Content-Length: 75
Content-Type: application/json
Date: Fri, 10 Aug 2018 02:22:36 GMT
Server: WSGIServer/0.2 CPython/3.6.4
X-Frame-Options: SAMEORIGIN

{
    "code": "撒有哪啦",
    "id": 4,
    "linenos": true,
    "title": ""
}

(django_venv) j:~/pythonfile$ http http://127.0.0.1:8000/snip/
HTTP/1.0 200 OK
Content-Length: 337
Content-Type: application/json
Date: Fri, 10 Aug 2018 02:22:40 GMT
Server: WSGIServer/0.2 CPython/3.6.4
X-Frame-Options: SAMEORIGIN

[
    {
        "code": "哈哈",
        "id": 1,
        "linenos": true,
        "title": ""
    },
    {
        "code": "嘻嘻",
        "id": 2,
        "linenos": true,
        "title": ""
    },
    {
        "code": "哼哼",
        "id": 3,
        "linenos": true,
        "title": ""
    },
    {
        "code": "撒有哪啦",
        "id": 4,
        "linenos": true,
        "title": ""
    }
]

(django_venv) j:~/pythonfile$ http http://127.0.0.1:8000/snip/2/
HTTP/1.0 200 OK
Content-Length: 63
Content-Type: application/json
Date: Fri, 10 Aug 2018 02:22:53 GMT
Server: WSGIServer/0.2 CPython/3.6.4
X-Frame-Options: SAMEORIGIN

{
    "code": "嘻嘻",
    "id": 2,
    "linenos": true,
    "title": ""
}

(django_venv) j:~/pythonfile$ http put http://127.0.0.1:8000/snip/2/ code="嘻唰唰"
HTTP/1.0 200 OK
Content-Length: 69
Content-Type: application/json
Date: Fri, 10 Aug 2018 02:23:20 GMT
Server: WSGIServer/0.2 CPython/3.6.4
X-Frame-Options: SAMEORIGIN

{
    "code": "嘻唰唰",
    "id": 2,
    "linenos": true,
    "title": ""
}

(django_venv) j:~/pythonfile$ http delete http://127.0.0.1:8000/snip/3/
HTTP/1.0 204 No Content
Content-Length: 0
Content-Type: text/html; charset=utf-8
Date: Fri, 10 Aug 2018 02:23:44 GMT
Server: WSGIServer/0.2 CPython/3.6.4
X-Frame-Options: SAMEORIGIN

(django_venv) j:~/pythonfile$ http http://127.0.0.1:8000/snip/
HTTP/1.0 200 OK
Content-Length: 278
Content-Type: application/json
Date: Fri, 10 Aug 2018 02:23:53 GMT
Server: WSGIServer/0.2 CPython/3.6.4
X-Frame-Options: SAMEORIGIN

[
    {
        "code": "哈哈",
        "id": 1,
        "linenos": true,
        "title": ""
    },
    {
        "code": "嘻唰唰",
        "id": 2,
        "linenos": true,
        "title": ""
    },
    {
        "code": "撒有哪啦",
        "id": 4,
        "linenos": true,
        "title": ""
    }
]

当然,您也可以通过浏览器来访问这些URL来显示出相同的JSON。

以上就是全部内容了,欢迎各位评论。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值