Win10 환경에서 Django2의 REST API를 사용해보십시오.
전제
Windows 10에 Python이나 Django2를 설치하는 기사는 간단하기 때문에 생략
결국 minishift에서 Django2의 REST API를 시도하고 싶어서 시행 착오 해보십시오.
minishift로 만들기 전에 Django2 소스를 만들어 둡니다.
환경
Django2 설치
C:\Users\tak>pip --version
pip 18.1 from c:\python\python37\lib\site-packages\pip (python 3.7)
C:\Users\tak>pip install django==2.1.4
Collecting django==2.1.4
Using cached https://files.pythonhosted.org/packages/fd/9a/0c028ea0fe4f5803dda1a7afabeed958d0c8b79b0fe762ffbf728db3b90d/Django-2.1.4-py3-none-any.whl
Collecting pytz (from django==2.1.4)
Downloading https://files.pythonhosted.org/packages/f8/0e/2365ddc010afb3d79147f1dd544e5ee24bf4ece58ab99b16fbb465ce6dc0/pytz-2018.7-py2.py3-none-any.whl (506kB)
100% |████████████████████████████████| 512kB 1.1MB/s
Installing collected packages: pytz, django
Successfully installed django-2.1.4 pytz-2018.7
마찬가지로 필요한 모듈을 설치합니다.
C:\Users\tak>pip install djangorestframework
C:\Users\tak>pip install django-filter
:
Local 환경에서 Django2의 매우 간단한 REST API 만들기
eclipse를 시작하고 새로운 PyDev Django 프로젝트 "smaple"을 만듭니다.
APP를 만듭니다.
c:\>cd rest\sample
c:\rest\sample>python manage.py startapp restapi
자체 APP를 등록합니다.
sample/setting.pyINSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework', # 追加
'restapi', # 追加
]
TIMEZONE을 설정합니다.
sample/setting.py# Internationalization
# https://docs.djangoproject.com/en/2.1/topics/i18n/
LANGUAGE_CODE = 'ja' # 修正
TIME_ZONE = 'Asia/Tokyo' # 修正
끝에 resto framework 설정을 추가합니다.
글쎄, 이번에는 필요하지 않지만 (웃음)
sample/setting.py# rest framework Internationalization
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 10
}
url을 등록합니다.
sample/urls.py"""sample URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.1/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
from restapi import views # 追加
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', views.current_time, name='current_time'), # 追加
]
이번에는 쉽게 현재 시간을 JSON 형식으로 만드는 것만 큼 간단했습니다.
restapi/views.pyfrom datetime import datetime
from django.http import JsonResponse
from rest_framework import status
from rest_framework.decorators import api_view
# Create your views here.
@api_view(['GET'])
def current_time(request):
ret = {'now':str(datetime.now())}
return JsonResponse(ret, status=status.HTTP_200_OK)
테스트용 코드를 씁니다만, 여기도 옆으로 착용해 리턴 코드( HTTP_200_OK
)의 확인만으로 합니다.
restapi/test.pyfrom django.urls import reverse
from rest_framework import status
from rest_framework.test import APITestCase
# Create your tests here.
class restapiTest(APITestCase):
def test_current_time(self):
url = reverse('current_time')
response = self.client.get(url, '')
self.assertEqual(response.status_code, status.HTTP_200_OK)
일단, makemigrations
& migrate
c:\rest\sample>python manage.py makemigrations
No changes detected
c:\rest\sample>python manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
Applying admin.0002_logentry_remove_auto_add... OK
Applying admin.0003_logentry_add_action_flag_choices... OK
Applying contenttypes.0002_remove_content_type_name... OK
Applying auth.0002_alter_permission_name_max_length... OK
Applying auth.0003_alter_user_email_max_length... OK
Applying auth.0004_alter_user_username_opts... OK
Applying auth.0005_alter_user_last_login_null... OK
Applying auth.0006_require_contenttypes_0002... OK
Applying auth.0007_alter_validators_add_error_messages... OK
Applying auth.0008_alter_user_username_max_length... OK
Applying auth.0009_alter_user_last_name_max_length... OK
Applying sessions.0001_initial... OK
에서 디버그 모드에서 실행 브라우저에서 http://127.0.0.1:8080/api/
에 액세스하면 이런 식으로 JSON을 얻을 수 있습니다.
{"now": "2018-12-26 14:00:29.432784"}
나중에 알았던 것 (readinessProbe, livenessProbe에 대한 대응)
목표는 minishift에서 Django2를 움직이는 것이기 때문에 ...
나중에 깨달았습니다만 minishift(openshift)로 Pod의 헬스 체크가 담겨 있습니다.
그 내용은 URL의 루트에 액세스해 200_OK를 돌려줄지 어떨지.
따라서 URL 루트에 액세스한 경우 빈 콘텐츠를 반환하도록 수정합니다.
restapi/views.pyfrom datetime import datetime
from django.shortcuts import render
from django.http import JsonResponse, HttpResponse
from rest_framework import status
from rest_framework.decorators import api_view
# Create your views here.
@api_view(['GET'])
def current_time(request):
ret = {'now':str(datetime.now())}
return JsonResponse(ret, status=status.HTTP_200_OK)
def health(request):
return HttpResponse('')
sample/urls.py"""sample URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.1/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
from restapi import views
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', views.current_time, name='current_time'),
path('', views.health, name='health'), # ここを追加
]
Reference
이 문제에 관하여(Win10 환경에서 Django2의 REST API를 사용해보십시오.), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다
https://qiita.com/imp555sti/items/cbe579fbbfa3837075f3
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)
c:\>cd rest\sample
c:\rest\sample>python manage.py startapp restapi
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework', # 追加
'restapi', # 追加
]
# Internationalization
# https://docs.djangoproject.com/en/2.1/topics/i18n/
LANGUAGE_CODE = 'ja' # 修正
TIME_ZONE = 'Asia/Tokyo' # 修正
# rest framework Internationalization
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 10
}
"""sample URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.1/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
from restapi import views # 追加
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', views.current_time, name='current_time'), # 追加
]
from datetime import datetime
from django.http import JsonResponse
from rest_framework import status
from rest_framework.decorators import api_view
# Create your views here.
@api_view(['GET'])
def current_time(request):
ret = {'now':str(datetime.now())}
return JsonResponse(ret, status=status.HTTP_200_OK)
from django.urls import reverse
from rest_framework import status
from rest_framework.test import APITestCase
# Create your tests here.
class restapiTest(APITestCase):
def test_current_time(self):
url = reverse('current_time')
response = self.client.get(url, '')
self.assertEqual(response.status_code, status.HTTP_200_OK)
c:\rest\sample>python manage.py makemigrations
No changes detected
c:\rest\sample>python manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
Applying admin.0002_logentry_remove_auto_add... OK
Applying admin.0003_logentry_add_action_flag_choices... OK
Applying contenttypes.0002_remove_content_type_name... OK
Applying auth.0002_alter_permission_name_max_length... OK
Applying auth.0003_alter_user_email_max_length... OK
Applying auth.0004_alter_user_username_opts... OK
Applying auth.0005_alter_user_last_login_null... OK
Applying auth.0006_require_contenttypes_0002... OK
Applying auth.0007_alter_validators_add_error_messages... OK
Applying auth.0008_alter_user_username_max_length... OK
Applying auth.0009_alter_user_last_name_max_length... OK
Applying sessions.0001_initial... OK
{"now": "2018-12-26 14:00:29.432784"}
목표는 minishift에서 Django2를 움직이는 것이기 때문에 ...
나중에 깨달았습니다만 minishift(openshift)로 Pod의 헬스 체크가 담겨 있습니다.
그 내용은 URL의 루트에 액세스해 200_OK를 돌려줄지 어떨지.
따라서 URL 루트에 액세스한 경우 빈 콘텐츠를 반환하도록 수정합니다.
restapi/views.py
from datetime import datetime
from django.shortcuts import render
from django.http import JsonResponse, HttpResponse
from rest_framework import status
from rest_framework.decorators import api_view
# Create your views here.
@api_view(['GET'])
def current_time(request):
ret = {'now':str(datetime.now())}
return JsonResponse(ret, status=status.HTTP_200_OK)
def health(request):
return HttpResponse('')
sample/urls.py
"""sample URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.1/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
from restapi import views
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', views.current_time, name='current_time'),
path('', views.health, name='health'), # ここを追加
]
Reference
이 문제에 관하여(Win10 환경에서 Django2의 REST API를 사용해보십시오.), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://qiita.com/imp555sti/items/cbe579fbbfa3837075f3텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)