Django使用rest_framework寫出API
在Django中用rest_framework寫API,寫了一個用戶注冊的API,并測試成功。
本人環(huán)境:Django==2.2.1;djangorestframework==3.11.0
1、安裝djangorestframework
(1)終端中輸入命令:
pip install djangorestframework
(2)在settings里面的INSTALL_APP里面,添加rest_framework應(yīng)用:
INSTALL_APP = [ ... ’rest_framework’,]
2、新建django項(xiàng)目和應(yīng)用:
django-admin startproject magic_chat
django-admin startapp chat_user #(進(jìn)入magic_chat目錄下)
python manage.py migrate # 數(shù)據(jù)寫入
3、在settings里面的INSTALL_APP里面,配置應(yīng)用:
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、配置項(xiàng)目的urls.py
urlpatterns = [ path(’admin/’, admin.site.urls), path(’’, include(’chat_user.urls’)),]
6、配置應(yīng)用的urls.py
from django.urls import pathfrom . import viewsurlpatterns = [ path(’register/’, views.Register.as_view()), ]
7、啟動服務(wù):
python manage.py runserver
8、驗(yàn)證API可調(diào)用:
打開Postman軟件,輸入網(wǎng)址http://127.0.0.1:8000/register/,輸入?yún)?shù),選擇post方式,send發(fā)送后成功返回'status': 200,'msg': '用戶注冊成功',說明API正常。
補(bǔ)充:如果報csrf的錯,則在請求的headers部分加入鍵:X-CSRFToken ,值是cookie中的csrftoken值,再次發(fā)送請求。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. python excel和yaml文件的讀取封裝2. python如何實(shí)現(xiàn)word批量轉(zhuǎn)HTML3. python3實(shí)現(xiàn)往mysql中插入datetime類型的數(shù)據(jù)4. moment轉(zhuǎn)化時間戳出現(xiàn)Invalid Date的問題及解決5. python爬蟲實(shí)戰(zhàn)之制作屬于自己的一個IP代理模塊6. Python中內(nèi)建模塊collections如何使用7. 關(guān)于 Android WebView 的內(nèi)存泄露問題8. Spring boot整合連接池實(shí)現(xiàn)過程圖解9. java虛擬機(jī)詳述-第三章(二)10. Android中的緩存
