安装
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/
目前只会一小部分,还需要加深学习。