🦁

【Django】Pythonで作るRest API【7Viewの設定】

2023/01/25に公開

【7Viewの設定】

YouTube: https://youtu.be/JAOdymb6yNU

https://youtu.be/JAOdymb6yNU

今回は「View」の設定を行います。

Viewの設定方法にはいくつかやり方がありまして、

クラスを使用する方法、

https://docs.djangoproject.com/ja/4.1/topics/class-based-views/

関数を使用する方法等があるのですが、
今回は関数を使用する方法で実践していきます。

今回はサンプルとして、

http://localhost:8000/posts/hello/

こちらにブラウザでアクセスしたら、
「Hello World」と返すViewを作成します。

myapp/posts/views.py
from django.shortcuts import render
from django.http import HttpResponse

# Create your views here.
def helloWorld(request):
  return HttpResponse('Hello World')

Viewの作成ができましたら、
ルートの設定を行います。

「posts」のフォルダ内に「urls.py」を作成します。

myapp/posts/urls.py
from django.urls import path
from .views import helloWorld

urlpatterns = [
    path('hello/', helloWorld, name='hello'),
]

そして「posts」で設定した「urls.py」を読み込むために
「myapp」-> 「urls.py」を開いて以下の設定を追加します。

myapp/myapp/urls.py
"""myapp URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/4.0/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('posts/', include('posts.urls')),
]

上記2つの「urls.py」を作成することで
最終的に

http://localhost:8000/posts/hello/

こちらのルートが有効となります。

Discussion