Python-Framework/Python-Framework__Django

django rest api

말하는감자 2021. 1. 20. 16:46

설치

  1. python3.x

  2. pip install djangorestframework

  3. pip install django

생성

  1. 프로젝트 생성

    django-admin startproject django_project
  2. app 생성

    python manage.py startapp first

설정

  1. django_project.settings.py
    ALLOWED_HOSTS를 ['*']으로 바꿔주고
    INSTALLED_APPS에 rest_framework와 방금 생성한 app을 등록

    ...생략...
    ALLOWED_HOSTS = ['*']
    INSTALLED_APPS = [
     'django.contrib.admin',
     'django.contrib.auth',
     'django.contrib.contenttypes',
     'django.contrib.sessions',
     'django.contrib.messages',
     'django.contrib.staticfiles',
     'rest_framework',
     'first.apps.FirstConfig',
    ]
    ...생략...
  2. django_proejct.urls.py

    from django.conf.urls import url, include
    from django.contrib import admin
    urlpatterns = [
     url(r'^admin/', admin.site.urls),
     url(r'^first/', include('first.urls')),
    ]

    위 내용을 적용해주면 localhost:8000/first 를 호출했을때 방금 생성한 first app의 urls.py와 매칭된다

app 작성

  1. first.model.py

    from django.db import models
    
    class FirstTable(models.Model):
    no = models.AutoField(db_column='no', primary_key=True)
    date = models.DateField(db_column='date', blank=True, null=True)
    test = models.CharField(db_column='test', max_length=100, blank=True, null=True)

2. first.serializers.py

from rest_framework import serializers
from first.models import FirstTable

class FirstTableSerializer(serializers.ModelSerializer):
  class Meta:
  	model = FirstTable
  	fields = ('no', 'date', 'test')

  def create(self, kwargs):
      return FirstTable.objects.create(**kwargs)

  def update(self, instance, **kwargs):
      instance.date = kwargs.get('date_', instance.date)
      instance.test = kwargs.get('test', instance.test)
      instance.save()
      return instance

 

3. first.views.py

from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response

from first.models import FirstTable
from first.serializers import FirstTableSerializer


@api_view(['GET', 'POST'])
def list_first(req, format=None):
    if req.method == 'GET':
        first_table = FirstTable.objects.all()
        serializer = FirstTableSerializer(first_table, many=True)
        return Response(serializer.data)
    elif req.method == 'POST':
        serializer = FirstTableSerializer(data=req.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


# date로 호출하기
@api_view(['GET'])
def details_first_by_date(req, date, format=None):
    from datetime import datetime
    date = datetime.strptime(date, '%Y-%m-%d')
    try:
        first_table = FirstTable.objects.filter(date=date).values()
    except Exception as e:
        print(e)
        return Response(status=status.HTTP_404_NOT_FOUND)

    serializer = FirstTableSerializer(first_table)
    return Response(serializer.instance)


# no로 호출하기
@api_view(['GET', 'PUT', 'DELETE'])
def details_first_by_no(req, no, format=None):
    try:
        first_table = FirstTable.objects.filter(no=no).values()
    except Exception as e:
        print(e)
        return Response(status=status.HTTP_404_NOT_FOUND)

    if req.method == 'GET':
        serializer = FirstTableSerializer(first_table)
        return Response(serializer.instance)
    elif req.method == 'PUT':
        serializer = FirstTableSerializer(first_table, data=req.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
    elif req.method == 'DELETE':
        first_table.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)

 

4. first.urls.py

from django.conf.urls import url
from rest_framework.urlpatterns import format_suffix_patterns
from first import views

urlpatterns = [
    url(r'^$', views.list_first),
    url(r'^date/(?P<date>\d{4}-\d{2}-\d{2})/$', views.details_first_by_date),
    url(r'^no/(?P<no>[0-9]+)/$', views.details_first_by_no),
]
urlpatterns = format_suffix_patterns(urlpatterns)

 

migration

python manage.py migrate
python manage.py makemigrations

'Python-Framework > Python-Framework__Django' 카테고리의 다른 글

django rest api  (0) 2021.01.20
django table drop  (0) 2021.01.13
django rest api 2) 프로젝트 실행하기  (0) 2019.09.06
django rest api 1) 초기 셋팅  (0) 2019.09.06
2) Detail 구현  (0) 2019.01.10
1) 프로젝트 생성 및 연결  (0) 2019.01.08
1 2 3 4 5 6