コンテンツにスキップ

Django

python製のWebフレームワーク https://www.djangoproject.com/

環境コピペ用(Ubuntu 18.04向け)

sudo apt-get install -y git python3-venv
PROJECT=$(basename ${PWD})
python3 -m venv ~/.virtualenvs/${PROJECT}
ln -s ~/.virtualenvs/${PROJECT}/bin/activate
source activate

Install and initialize

pip install django
django-admin startproject project
cd project
python manage.py makemigrations
python manage.py migrate
python manage.py createsuperuser
python manage.py startapp app

その他Tips

認証

アプリケーションの分割単位

良く分からん。データベース分割が可能な単位にするという意見は分かる。予見できない場合は1アプリにした方が良さそう。
認証・認可・通知・問い合わせ辺りは再利用性が高そうなので別にするといいかも。

特定のサブネットからのアクセスを許可したい場合

pip install django-allow-cidr

settings.py に以下を追加

ALLOWED_CIDR_NETS = ['192.168.0.0/16', '172.16.0.0/16']

MIDDLEWARE = [
  ...
  'allow_cidr.middleware.AllowCIDRMiddleware',
]

RESTful APIだけに特化する場合

Setup

pip install django djangorestframework
django-admin startproject project
cd project
python manage.py makemigrations
python manage.py migrate
python manage.py startapp probes

probes/models.py

from django.db import models
import uuid


class Probe(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    name = models.CharField(max_length=128)
    vendor = models.CharField(max_length=128, null=True)
    hostname = models.CharField(max_length=128)
    port = models.IntegerField(default=22)
    username = models.CharField(max_length=128)
    password = models.CharField(max_length=128, null=True)
    private_key = models.CharField(max_length=2048, null=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.name

probes/admin.py

from django.contrib import admin

from .models import Probe


@admin.register(Probe)
class ProbeAdmin(admin.ModelAdmin):
    pass

probes/serializer.py

from rest_framework import serializers
from .models import Probe


class ProbeSerializer(serializers.ModelSerializer):
    class Meta:
        model = Probe
        fields = ('id', 'name', 'vendor', 'hostname', 'port', 'username', 'password', 'private_key', 'created_at', 'updated_at')

probes/urls.py

from rest_framework import routers
from .views import ProbeViewSet


router = routers.DefaultRouter()
router.register(r'probes', ProbeViewSet)

probes/views.py

from django.shortcuts import render

from rest_framework import viewsets, filters
from .models import Probe
from .serializer import ProbeSerializer


class ProbeViewSet(viewsets.ModelViewSet):
    queryset = Probe.objects.all()
    serializer_class = ProbeSerializer

project/urls.py

from django.contrib import admin
from django.urls import path, include
from probes.urls import router as probe_router

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

project/settings.py

INSTALLED_APPS = [
    ...
    'probes',
    'rest_framework',
]

確認

http://127.0.0.1:8000/api/ にアクセスすると、APIが確認できる。

$ curl -s http://127.0.0.1:8000/api/ | jq
{
  "probes": "http://127.0.0.1:8000/api/probes/"
}
$ curl -X POST -H 'Content-Type: application/json' http://127.0.0.1:8000/api/probes/ -d '''{
    "name": "example",
    "vendor": "linux",
    "hostname": "localhost",
    "port": 22,
    "username": "admin",
    "password": "xxxxxxxxxx",
    "private_key": null
  }'''
$ curl -s http://127.0.0.1:8000/api/probes/ | jq
[
  {
    "id": "c299e7ab-3c6c-491d-ae1c-2cd069ad78ad",
    "name": "example",
    "vendor": "linux",
    "hostname": "localhost",
    "port": 22,
    "username": "admin",
    "password": "xxxxxxxxxx",
    "private_key": null,
    "created_at": "2019-04-16T02:34:39.880291Z",
    "updated_at": "2019-04-16T02:34:39.880334Z"
  }
]
$ curl -s http://127.0.0.1:8000/api/probes/c299e7ab-3c6c-491d-ae1c-2cd069ad78ad/ | jq
{
  "id": "c299e7ab-3c6c-491d-ae1c-2cd069ad78ad",
  "name": "example",
  "vendor": "linux",
  "hostname": "localhost",
  "port": 22,
  "username": "admin",
  "password": "xxxxxxxxxx",
  "private_key": null,
  "created_at": "2019-04-16T02:34:39.880291Z",
  "updated_at": "2019-04-16T02:34:39.880334Z"
}
$ curl -X DELETE http://127.0.0.1:8000/api/probes/c299e7ab-3c6c-491d-ae1c-2cd069ad78ad/
$ curl -s http://127.0.0.1:8000/api/probes/ | jq
[]

最終更新日: 2021-05-19 14:16:14