Django中,用rest_framework写API
在Django中用rest_framework写API,写了一个用户注册的API,并测试成功。
本人环境:Django==2.2.1;djangorestframework==3.11.0
1、安装djangorestframework
(1)终端中输入命令:
pip install djangorestframework
(2)在settings里面的INSTALL_APP里面,添加rest_framework应用:
INSTALL_APP = [
...
'rest_framework',
]
2、新建django项目和应用:
django-admin startproject magic_chat
django-admin startapp chat_user #(进入magic_chat目录下)
python manage.py migrate # 数据写入
3、在settings里面的INSTALL_APP里面,配置应用:
INSTALL_APP = [
...
'rest_framework',
'chat_user.apps.ChatUserConfig',
]
4、在views.py中写API代码:
from django.contrib.auth.models import User from rest_framework import status from rest_framework.response import Response from rest_framework.views import APIView class Register(APIView): def post(self,request): """ 注册 """ username = request.data.get('username') password = request.data.get('password') user = User.objects.create_user(username=username,password=password) user.save() context = { "status":status.HTTP_200_OK, "msg":"用户注册成功" } return Response(context)
5、配置项目的urls.py
urlpatterns = [ path('admin/', admin.site.urls), path('', include('chat_user.urls')), ]
6、配置应用的urls.py
from django.urls import path from . import views urlpatterns = [ path('register/', views.Register.as_view()), ]
7、启动服务:
python manage.py runserver
8、验证API可调用:
打开Postman软件,输入网址http://127.0.0.1:8000/register/,输入参数,选择post方式,send发送后成功返回"status": 200,"msg": "用户注册成功",说明API正常。
补充:如果报csrf的错,则在请求的headers部分加入键:X-CSRFToken ,值是cookie中的csrftoken值,再次发送请求。