学习Django RESTFramework (1)
亚马逊Linux发布2版(Karoo)。
裝備自己
# 作業ディレクトリ作成
cd
mkdir -p work
cd work
# 仮想環境作成
python3 -m venv ~/py37/
# 仮想環境に切り替え
source ~/py37/bin/activate
# Django、DangoRestFrameworkをインストール
pip install django
pip install djangorestframework
# プロジェクト作成
django-admin startproject djangorestframework_sample
cd djangorestframework_sample
django-admin startapp restapi001
接下来,打开djangorestframework_sample/settings.py文件,将”rest_framework”添加到INSTALLED_APPS中。
vi settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
]
View的实现(基于类和基于函数)
cd restapi001
vi views.py
from rest_framework.views import APIView
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import status
class HelloWorld(APIView):
"""
クラスベースのAPIView
・HTTPのメソッドがクラスのメソッドになるので、わかりやすい
"""
def get(self, request, format=None):
return Response({"message": "Hello World!!"},
status=status.HTTP_200_OK)
def post(self, request, format=None):
request_data = request.data
return Response({"message": request_data["message"]},
status=status.HTTP_201_CREATED)
@api_view(['GET', 'POST'])
def hello_world(request):
"""
関数ベースのAPIView
・実装がシンプルで、読みやすい
・GET, POSTなどを関数内で分岐させないといけない
"""
if request.method == 'GET':
return Response({"message": "Hello function base APIView GET!!"},
status=status.HTTP_200_OK)
elif request.method == 'POST':
if request.data:
request_data = request.data
return Response({"message": request_data["message"]},
status=status.HTTP_201_CREATED)
实现路由功能
vi urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.hello_world, name='hello'),
path('hello', views.HelloWorld.as_view(), name='test-get')
]
将代码实现到djangorestframework_sample/urls.py,以便读取restapi001/urls.py文件。
cd ..
cd djangorestframework_sample
vi urls.py
from django.urls import path, include
urlpatterns = [
path('restapi001/', include('restapi001.urls')),
path('admin/', admin.site.urls),
]
确认动作
python manage.py runserver





参考网址
Django REST Framework – 视图 –
总结Django REST Framework – 视图的用法 –
调查Django的函数视图和类视图的区别、优点和缺点