您的位置:首页技术文章
文章详情页

Django使用rest_framework写出API

【字号: 日期:2024-09-30 18:28:25浏览:28作者:猪猪

在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.modelsimport Userfrom rest_frameworkimport statusfrom rest_framework.responseimport Responsefrom rest_framework.viewsimport APIViewclass 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 pathfrom . import viewsurlpatterns = [ 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正常。

Django使用rest_framework写出API

补充:如果报csrf的错,则在请求的headers部分加入键:X-CSRFToken ,值是cookie中的csrftoken值,再次发送请求。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持好吧啦网。

标签: Django
相关文章: