djangorestframework 框架的使用(一)

安装
pip install djangorestframework==3.3.2
pip install Markdown

如果出现no module django.urls的错误,可能是版本不兼容,安装早期版本
安装 Markdown 是为了显示界面

注册restframework框架
settings.py中的INSTALLED_APPS在REST_FRAMEWORK可以写一些配置

INSTALLED_APPS = (
    ...
    "rest_framework",
)
# REST_FRAMEWORK = {
#     # Use Django's standard `django.contrib.auth` permissions,
#     # or allow read-only access for unauthenticated users.
#     'DEFAULT_PERMISSION_CLASSES': [
#         'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
#     ]
# }

序列化
在与models.py 同级下新建一个文件serializers.py

# -*- coding:utf-8 -*-
from rest_framework import serializers

class TodoSerializer(serializers.Serializer):
    task = serializers.CharField(max_length=1000)
    is_delete = serializers.BooleanField(default=False)
    ct = serializers.CharField(max_length=50)

    def create(self, validated_data):
        pass

    def update(self, instance, validated_data):
        pass

视图
views.py

from .models import Todo
from rest_framework.response import Response
from rest_framework.views import APIView
from .serializers import TodoSerializer

# Create your views here.

class TodoList(APIView):
    def get(self, request, format=None):
        todos = Todo.todo.filter(is_delete=False)
        ser = TodoSerializer(todos, many=True)
        return Response(ser.data)

配置url

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

urlpatterns = [
     ...
    url(r'^api/todo/$', views.TodoList.as_view()),
]

查看
输入 http://localhost:8000/api/todo/

djangorestframework 框架的使用(一)_第1张图片
Todo List

目前只会一小部分,还需要加深学习。

你可能感兴趣的:(djangorestframework 框架的使用(一))