我要在Win10环境下尝试使用Django2的REST API

前提 – need one option

由于已经有大量关于在Windows10上安装Python和Django2的文章,我们将省略此部分。

最终我想尝试在minishift上构建Django2的REST API,并且我会进行多次尝试和错误。

在开始使用minishift之前,我会先创建好Django2的源代码。

    • Win10環境でDjango2のREST APIを試してみる

 

    • minishift V1.28.0でDjango2を動かす①:テンプレート確認

 

    • minishift V1.28.0でDjango2を動かす②:テンプレート&s2iソースの作成

 

    • minishift V1.28.0でDjango2を動かす③:s2iソースの修正&ビルド

 

    • minishift V1.28.0でDjango2を動かす④:残課題

 

    • minishift V1.28.0でnginx+gunicorn+Django2を動かす

 

    • minishift V1.28.0でnginx+gunicorn+Django2を動かす。あっcreatesuperuser忘れてた(笑)

 

    openshiftに対応するためのDjango2コーディング時に気を付けるべき点

环境

    • Windows10

 

    • Python3.7.2 Release Date: 2018-12-24 → Python.org

Django2.1.4 Release Date: 2018-12-03 → django

djangorestframework3.9.0 → Django REST framework

eclipse OXYGEN → Marge Doc Project

安装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
:

在本地环境下使用Django2创建一个非常简单的REST API。

使用eclipse启动并创建一个名为”smaple”的新PyDev Django项目。

01.png

我将创建一个APP。

c:\>cd rest\sample
c:\rest\sample>python manage.py startapp restapi
02.png

我要注册我之前的应用程序。

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
}

我会注册这个URL。

"""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格式。

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)

我会编写测试代码,但这里只是懒散地确认返回代码(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)

暂时,执行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的根目录,则将修正为返回空内容。

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 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'),         # ここを追加
]
广告
将在 10 秒后关闭
bannerAds