[DRF] Open Api에서 데이터 받아와서 저장하기

JinUk Lee·2023년 8월 18일
0

프로그래머스

목록 보기
43/47

오픈 api를 사용하는데 api에서 받아온 데이터를 저장하는 방법이다.

게임에서 제공하는 api를 받아와서 캐릭터 데이터를 저장한다고 치자

models.py


# models.py

from django.db import models

class Character(models.Model):

    name = models.CharField(max_length=80)
    attack = models.DecimalField(max_digits=6, decimal_places=1)
    hp = models.DecimalField(max_digits=6, decimal_places=1)
    hpregen = models.DecimalField(max_digits=6, decimal_places=1)
    stamina = models.DecimalField(max_digits=6, decimal_places=1)
    stregen = models.DecimalField(max_digits=6, decimal_places=1)
    defense = models.DecimalField(max_digits=6, decimal_places=1)
    atkspeed = models.DecimalField(max_digits=6, decimal_places=1)
    speed = models.DecimalField(max_digits=6, decimal_places=1)

serializers.py


from rest_framework import serializers
from .models import Character



class CharacterSerializers(serializers.ModelSerializer):

    class Meta:
        model = Character
        fields = '__all__'

views.py


from django.shortcuts import render
from rest_framework.viewsets import ModelViewSet
# Create your views here.
from .models import *
from .serializers import *
import requests
from django.http import HttpResponse


class CharacterView(ModelViewSet):

    pagination_class = None

    queryset = Character.objects.all().order_by('id')
    serializer_class = CharacterSerializers


def Characterload(request):

    test = requests.get(
        'https://open-api.bser.io/v1/data/Character',
        headers={'x-api-key':'개인암호키'}
    )
    test_json = test.json()
    chlist = test_json['data']

    for i in chlist:
        try:
            tester_name = Character.objects.get(name=i['name'])
            continue

        except:

            Character(
                name = i['name'],
                attack = i['attackPower'],
                hp = i['maxHp'],
                hpregen = i['hpRegen'],
                stamina = i['maxSp'],
                stregen = i['spRegen'],
                defense = i['defense'],
                atkspeed = i['attackSpeed'],
                speed = i['moveSpeed'],
            ).save()


    return HttpResponse(chlist)

모델이나 시리얼라이저는 기존과 비슷하고 views.py 에서 api로 호출을 하고 데이터를 저장하는 코드를 작성했다.

python에서 응답을 보내고 받을땐 requests 패키지를 사용한다.

프론트에서의 axios 와 유사하게 사용되는 패키지라고 생각하면 된다.

그런 다음 받아온 데이터를 .json() 으로 json으로 변경해주고

같은 데이터를 중복해서 저장하지 않기위해서 try except 로 조건을 걸어준다.

objects.get 은 조건에 맞는 객체가 없으면 에러를 발생시키므로 사용하기에 적합하다.

(filter 는 조건에 맞는 객체가 없어도 오류가 발생하지 않는다.)

데이터를 가지고있지 않다면 save()를 통해 모델에 저장한다.

profile
개발자 지망생

0개의 댓글