Django RESTFrameworkの勉強(1)
Amazon Linux release 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を開き、 INSTALLED_APPSに、「'rest_framework',」を追加
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')
]
restapi001/urls.pyのファイルを読み込むためdjangorestframework_sample/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
ブラウザを起動し、http://127.0.0.1:8000/restapi001
関数ベースのAPIViewの動作確認 -以下のように入力してPOSTをクリック-
クラスベースのAPIViewの動作確認
http://127.0.0.1:8000/restapi001/hello にアクセス
参考URL
Django REST Framework -Views-
Django REST Framework -View の使い方をまとめてみた-
Djangoのfunction based viewとclass based viewの違い・メリット・デメリットを調べた
Author And Source
この問題について(Django RESTFrameworkの勉強(1)), 我々は、より多くの情報をここで見つけました https://qiita.com/rururu_kenken/items/c9e91f832ce760118e47著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .