본문 바로가기

Tutorial

[GraphQL] 그래프ql 시작하기 with PYTHON

반응형

이번 포스팅은 GraphQL에 관한 내용과

빠르게 시작 할 수 있는 튜토리얼에 관한 내용입니다.

 

 

 

1. GraphQL이란, 

가장 기본적으로는 페이스북에서 만들어진 쿼리언어이다. GraphQL은 sql과 마찬가지로 쿼리 언어이다. 

하지만 둘은 기본적으로 사용목적과 구조적인 차이가 있다.

 

- 우선 sql은 데이터베이스에 저장 된 데이터를 잘 가져오는 것을 목적으로하고,

gql 은 웹 클라이언트가 데이터를 서버로부터 효율적으로 가져오는 것이 목적임

 

- sql은 주로 백엔드 개발자가 작성하고 데이터를 호출하고,

sql은 보통 클라이언트 시스템에서 작성하고 호출함

 

 

2. python + graphql 시작하기

 

" 아래 튜토리얼을 유튜브를 참고하여 작성함 "

 

참고 링크 : https://www.youtube.com/watch?v=-0uxxht4mko

 

1> 파이썬 패키지 graphene 설치

$ pip install graphene

 

- 기본적으로 파이썬에서 graphql을 사용하기 위한 패키지 설치

 

2> 파이썬 파일 생성하여 QraphQL 사용 (기본 예제1)

아래는 가장 기본으로 테스트 한 예제 파일

import graphene
import json
from datetime import datetime

class User(graphene.ObjectType):
	id = graphene.ID()
    username = graphene.String()
    last_login = graphene.DateTime()
    

class Query(graphene.ObjectType):
	users = graphene.List(User, first=graphene.Int())
    
    def resolve_is_users(self, info, first):
    	return [
            User(username='Alice', last_login=datetime.now()),
            User(username='Bob', last_login=datetime.now()),
            User(username='Steven', last_login=datetime.now())
        ][:first]
    

schema = graphene.Schema(query=Query)

result = schema.execete(
	'''
    {
    	users(first: 1) {
        	username
            lastLogin
        }
    }
    '''
)

item = dict(result.data.item())

print(json.dumps(items, indent=4)

 

- 파이썬에서 graphql를 정의하고 실제로 요청하는 예제

 

3> GraphQL 사용 (기본 예제2) : Mutation

import graphene
import json
from datetime import datetime

class User(graphene.ObjectType):
	id = graphene.ID()
    username = graphene.String()
    last_login = graphene.DateTime(required=False)
    

class Query(graphene.ObjectType):
	users = graphene.List(User, first=graphene.Int())
    
    def resolve_is_users(self, info, first):
    	return [
            User(username='Alice', last_login=datetime.now()),
            User(username='Bob', last_login=datetime.now()),
            User(username='Steven', last_login=datetime.now())
        ][:first]
    
class CreateUser(graphene.Mutation):

	class Arguments:
    	username = graphene.String()
        
    user = graphene.Field(User)
    
    def mutate(self, info, username):
    	if info.context.get('is_vip'):
    		username = username.upper()
    	user = User(username=username)
        return CreateUser(user=user)
        

class Mutations(graphene.ObjectType):
	create_uer = CreateUser.Field()


schema = graphene.Schema(query=Query, mutation=Mutations)


result = schema.execete(
	'''
    mutation createUser($username: String) {
        createUser(username: $username){
            user {
                username
            }
        }
    }
    ''',
    variable_values={'username':'Bob'},
    context={'is_vip': True}
)

item = dict(result.data.item())

print(json.dumps(items, indent=4)

 

 

3. Graph QL + Django 사용

1> 파이썬 패키지 설치

$ pip install graphene-django

 

- 장고에서 graphene을 사용하기 위해 필요한 패키지 설치

 

2> 장고 settings.py 에 앱 추가

$ vi settings.py


INSTALLED_APPS = [
	...
	...
    '[앱 이름]'
	'graphene_django'
]

- 설치한 패키지를 장고 앱으로 추가해준다.

 

3> 테스트 파일 생성

$ vi snippets/models.py

# 테스트 하기 위한 간단한 모델.py 생성
from django.db import models

class Snippet(models.Model):
    title = models.CharField(max_length=100)
    body = models.TextField()
    created = models.DateTimeField(auto_now_add=True)
    
    def __str__(self):
    	return self.title
    
    def body_preview(self):
    	return self.body[:50]

- Snippet모델(데이터)에 대한 구조

 

$ vi snippets/schema.py

import graphene
from graphene_django.types import DjangoObjectType
from .models import Snippet

class SnippetType(DjangoObjectType):

    class Meta:
    	model = Snippet

class Query(graphene.ObjectType):
    all_snippets = graphene.List(SnippetType)
    
    def resolve_all_snippets(self, info, **kwargs):
    	return Snippet.objects.all()

- 장고 프로젝트에서 새로 생성한 앱(snippets) 폴더 안쪽에 파일 생성

 

$ vi 기본폴더/schema_re.py

import graphene
from snippets.schema import Query as snippets_query


class Query(snippets_query):
    pass

schema_re = graphene.Schema(query=Query)

- 쿼리를 요청하는 schema_re.py를 다시 생성한다. (기본 프로젝트 폴더 안에 작성)

 

$ vi 기본폴더/urls.py

from graphene_django.views import GraphQLView
from django.urls import path, include
import .schema_re import schema_re

urlpatterns = [
    path('graphql/', GraphQLView.as_view(
    	graphiql=True
    	schema=schema_re
    )),
]

- urlpatterns 에 graphql을 추가하고, 위에서 작성한 schema_re와 연결함.

 

4> 테스트 진행

$ python manage.py runserver

- 테스트를 위한 장고 서버 실행

 

http://localhost:8000/graphql/

- 위 주소로 접근하면, graphiql에 접속 할 수 있음

- graphiql에 접속하여 원하는 요청을 보내면 결과를 받을 수 있다.

 

< 실제 GraphiQL 화면>

 

 

4. GraphQL 쿼리 작성 가이드

참고링크 : https://www.youtube.com/watch?v=omSpI1Nu_pg

 

반응형