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.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正常。
補充:如果報csrf的錯,則在請求的headers部分加入鍵:X-CSRFToken ,值是cookie中的csrftoken值,再次發送請求。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。
相關文章:
