(1) Basic REST API(기본 REST api 만들기)_영어쌤이 만드는 회원가입...
- 공유 링크 만들기
- X
- 이메일
- 기타 앱
(1) Basic REST API(기본 REST api 만들기)_영어쌤이 만드는 회원가입...
죠니클럽 SuperCodeParty
2019. 5. 21. 14:10
(1) Basic REST API_영어쌤이 만드는 회원가입, 인증[CRUD] 만들어욤!
안녕하세요? 웹개발하는 영어썜 죠니입니다. 이런 것 처음이에요. 앞서 언급했듯이 튜토리얼 형식 그대로 진행하며 개인적으로 느꼈던 주의사항을 적어 볼게요~.
Let's get started, shall we?
1. 파이썬 버전 확인
$ python3 --version
2. 파이썬 가상화 설치 및 실행
$ pip3 install pipenv
# pipenv 설치가 완료되면 다음의 명령어를 통해 가상환경으로 들어갑니다.
$ pipenv shell
3. 장고, 장고레스트, 녹스 설치(가상환경 내에서...)
$ pipenv install django djangorestframework django-rest-knox
# 설치완료 확인
$ vi Pipfile
# 위의 명령어를 통해 해당 파일에 들어가면 설치된 패키지를 볼 수 있습니다.
# 장고프로젝트 만들기(가상환경 내에서...)
$ django-admin startproject leadmanager
$ cd leadmanager
$ python manage.py startapp leads
5. /leadmanager/settings.py 수정
1 2 3 4 5 INSTALLED_APPS = [ ... 'leads' , 'rest_framework' , ] cs
6. /leads/models.py 수정, 모델 만들기
1 2 3 4 5 6 7 from django.db import models models class Lead( Lead( models.Model): name = models.CharField(max_length = 100 ) email = models.EmailField(max_length = 100 , unique = True) message = models.CharField(max_length = 500 , blank = True) created_at = models.DateTimeField(auto_now_add = True)
7. makemigrations leads(가상환경 내에서...)
$ python manage.py makemigrations leads
위의 명령어를 실행하면 다음과 같은 결과를 얻게 됩니다.
leads/migrations/0001_initial.py 의 내용은 다음과 같습니다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 from django.db import migrations, models migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name = 'Lead' , fields = [ ( 'id' , models.AutoField(auto_created = True, primary_key = True, serialize = False, verbose_name = 'ID' )), ( 'name' , models.CharField(max_length = 100 )), ( 'email' , models.EmailField(max_length = 100 , unique = True)), ( 'message' , models.CharField(blank = True, max_length = 500 )), ( 'created_at' , models.DateTimeField(auto_now_add = True)), ], ), ] http://colorscripter.com/info#e " target="_blank" style="color:#4f4f4f; text-decoration:none">Colored by Color Scripter
마이그레이션 한번 더 해서 위의 것들 추가하기(가상환경)
$ python manage.py migrate
다음: Serializer 관련
/leads/serializers.py 작성
1 2 3 4 5 6 7 8 from rest_framework import serializers from leads.models import Lead Lead # Lead Serializer class LeadSerializer(serializers.ModelSerializer): class Meta: model = Lead fields = '__all__'
/leads/api.py 작성
1 2 3 4 5 6 7 8 9 10 11 12 from leads.models import Lead Lead from rest_framework import viewsets, permissions from .serializers import LeadSerializer # Lead Viewset class LeadViewSet(viewsets.ModelViewSet): = Lead.objects.all() queryset permission_classes = [ permissions.AllowAny ] serializer_class = LeadSerializer http://colorscripter.com/info#e " target="_blank" style="color:#4f4f4f; text-decoration:none">Colored by Color Scripter
위와 같이 파이썬 코드 작성 시에 permissions도 있고 s를 뺀 permission 도 있어요. 토씨 하나 틀리지 않는 것이 좋다고 말씀드리는 바 입니다.
/leadmanager/urls.py 수정
이번엔 leads 가 아닌 leadmanager 디렉터리(폴더)로 옮겨가 주세요. 그 안의 urls.py 파일을 수정해 줄 것 입니다.
1 2 3 4 5 6 7 from django.contrib import admin from django.urls import path, include path, include urlpatterns = [ '' , include( leads.urls' path(, include()), ] http://colorscripter.com/info#e " target="_blank" style="color:#4f4f4f; text-decoration:none">Colored by Color Scripter
urls.py의 기존의 내용에서 위와 같이 수정을 해 줍니다. 특히 실수로 2번째 줄의 include 와 같이 선언을 해 주지 않는 일도 있으니 주의 해 주세요. 또 5번째 줄의 path를 위와 같이 수정해 주시면 됩니다.
/leads/urls.py 만들기, 작성하기
다시 leads 디렉터리(폴더)로 옮겨와 urls.py 파일을 만들어 작성해 줍니다.
1 2 3 4 5 6 7 from rest_framework import routers from .api import LeadViewSet router = routers.DefaultRouter() router.register( 'api/leads' , LeadViewSet, 'leads' ) = router.urls urlpatterns
8. 테스트하기 전에...
이제 다 되었으니 테스트로 실행하여야 겠죠?
만약 여러분이 로컬 환경에서만 진행하신다면 큰 문제는 없을겁니다. 그렇지만 실무에선 최소한 사내에서 동작하도록 하는게 저희 회사에선 정석이라서 대부분에선 누락된 그 부분을 포함하겠습니다.
8.1. 모든 호스트에 해당 서버 포트 페이지에 접근 허용해 주기
8.1.a. /leadmanager/setting.py 수정
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) BASE_DIR # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '0h!w-(cl-8hsic5pzs_1_g@11v9wiqi%dhyqq==acnc%vhh-n=' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True # 아래의 코드에 '*' 넣어주면 됨 ALLOWED_HOSTS = [ '*' ] # Application definition INSTALLED_APPS = [ django.contrib.admin' django.contrib.auth' 'django.contrib.contenttypes' , 'django.contrib.sessions' , 'django.contrib.messages' , 'django.contrib.staticfiles' , 'leads' , 'rest_framework' , ] http://colorscripter.com/info#e " target="_blank" style="color:#4f4f4f; text-decoration:none">Colored by Color Scripter
위의 코드에서 다음의 ALLOWED_HOSTS가 있는 줄을 수정하였습니다.
ALLOWED_HOSTS = ['*']
여기서 '*'는 에스터리스크 라고 부르고 선택자개념에선 모두(everyone)를 뜻합니다.
그리고 원하는 단어를 찾는 방법을 간략히 기재합니다.
코드를 수정중이었다면 esc 키 또는 Ctrl + c 를 입력해 주어 수정상태에서 벗어나면 / + (찾기를 원하는 단어)
예를 들어 저 위에서 ALLOWED_HOSTS를 찾으려면 다음과 같이 하시면 됩니다.
9. 파이썬 서버 실행하기
수정도 끝났고 모든 준비가 완료 되었으니 한번 실행해 봅니다.
$ python manage.py runserver
위의 명령어로 서버 실행은 되지만 브라우저로 접속이 되지 않는다면 다음의 명령어로 해 보세요.
$ python manage.py runserver 0:8000
위의 명령어로 실행 했을때 또 안되면 대부분 포트가 겹쳐서(이미 8000번 포트를 누가 쓰고 있다.) 그렇 것으로 판단이 됩니다. 그럴 땐 0:8001과 같이 다른 포트 번호를 넣어서 다시 해 보시면 좋습니다.
다음 순서는
포스트맨(rest api 정상 작동 테스트용)
을 활용하여 테스트 해 보기가 되겠습니다.
from http://hyunvinci.tistory.com/110 by ccl(S) rewrite - 2020-03-06 09:20:25
- 공유 링크 만들기
- X
- 이메일
- 기타 앱
댓글
댓글 쓰기