요약: poetry설치, 사용. DRF, simplejwt, cors-headers,yasg 설치 및 초기설정
오늘은 개인과제를 위한 셋팅을 했다. 처음으로 poetry를 이용해 의존성관리 및 가상환경 설정을 하면서 django프로젝트를 만들어 보기로 했다.
1. Poetry 설치 및 사용
1-0. Poetry란..
Poetry는 파이썬 의존성 관리를 위한 툴이다. poetry.lock을 이용해 서로 다른 환경에서도 동일한 패키지를 유지할 수 있고, 자동으로 poetry.toml과 poetry.lock을 갱신하고, 직접 패키지를 만들고(build) 배포(publish)할 수 있는 등 다양한 기능을 제공하며 가상환경도 함께 관리할 수 있는 아주 편리한 툴이다. 기존에 사용하는 requirements.txt 에 비해 훨씬 편리하고 의존성 패키지와 실제 필요한 패키지의 구분이 비교적 명확하다는 장점이 있다.
1-1. 시스템 전역에 poetry 설치
https://python-poetry.org/docs/master/
Introduction | master | Documentation | Poetry - Python dependency management and packaging made easy
If you installed using the deprecated get-poetry.py script, you should remove the path it uses manually, e.g. rm -rf "${POETRY_HOME:-~/.poetry}" Also remove ~/.poetry/bin from your $PATH in your shell configuration, if it is present.
python-poetry.org
위 사이트에 들어가면, 설치방법에 대한 설명이 나와있다.
MacOS, Linux의 경우 다음의 쉘 명령어를 입력해 설치할 수 있다.
curl -sSL https://install.python-poetry.org | python3 -
window의 경우 powershell에서 다음 명령어로 설치할 수 있다.
(Invoke-WebRequest -Uri https://install.python-poetry.org -UseBasicParsing).Content | py -
문제 발생:
ERROR: Unable to download webpage: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1123)> (caused by URLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1123)')))
MacOS에서 설치를 시도하자 위와 같은 오류가 발생하며 중간에 설치가 취소되었다. https 프로토콜로 접속하기 위한 SSL 인증서가 없어서 발생하는 문제인 것으로 보인다.
해결:
스택오버플로우에서 이와 비슷한 상황에 대한 해결 방법을 발견하였다.
Here are the steps for macOS:
1. Open the folder /Applications/Python 3.x (x is the version you are running).
2. Double click the Install Certificates.command. It will open a terminal and install the certificate.
위 파일을 더블 클릭한 후, zshell을 다시 실행하여 다시 설치를 시도해보니 해결되었다.
1-2. PATH에 추가
문제상황:
설치한 뒤 poetry --version 으로 설치가 잘 되었는지 확인하려하니, 설치가 되어있지 않다고 나오는데, 정작 다시 설치를 시도하면 잘 설치되어있다고 나온다.
해결:
이는 poetry의 명령어들을 아직 zshell이 모르기 때문이다. poetry 명령어가 저장되어있는 위치를 PATH에 추가하여야한다.
최초 설치 시 해당 위치는 $HOME/.local/bin이다.
따라서 home에 위치한 .zprofile의 가장 밑에
export PATH="/Users/imbo/.local/bin:$PATH"
한줄을 추가해주면 된다.
1-3. 설치 완료 후 사용
poetry를 사용하기 위해 알아야 하는 명령어는 다음과 같다.
poetry new <프로젝트명> | 새 프로젝트 만들기 |
poetry init | poetry.toml 만들기 |
poetry install | poetry.toml과 poetry.lock에 따라 패키지 설치 |
poetry add <패키지명> | 원하는 패키지를 설치하고 poetry.toml과 poetry.lock 갱신 |
poetry update | 패키지와 의존성 패키지의 버전을 최신화하고 poetry.toml과 poetry.lock 갱신 |
poetry env use python3 | 가상환경 생성 |
poetry shell | 가상환경 활성화 |
poetry env remove python3 |
가상환경 삭제 |
poetry run <명령어> | 해당 명령어를 가상환경 상에서 실행 |
* toml파일은
프로젝트의 의존성을 조율 해 주는 파일이기 때문에 가장 중요한 파일이다.
해당 파일은 다음과 같이 생겼다.
poetry는 패키지 이름과 버전정보를 repositories에서 패키지를 찾을 때 사용하며 tool.poetry.repositories(=패키지를 찾는 곳)는 기본적으로 PyPI이다.
pyproject.toml 파일을 변경할 필요 없이 add 명령어를 통해 자동으로 수정이 가능하다.
* lock 파일은
poetry.lock 파일이 없는 상태에서 install을 실행했을 경우, poetry는 pyprojet.toml에 있는 패키지들의 모든 의존성을 해결하고 가장 최신 버전으로 다운로드 하게 된다. 설치가 끝나면 패키지의 정확한 버전을 명시해 lock파일에 기록한다. lock 파일을 공유하여 모든 구성원들이 같은 버전의 의존성을 가질 수 있다. install을 실행했을 경우 이미 poetry.lock 파일이 있다면 일관성을 유지하기 위해 lock 설정에 맞는 파일을 다운받게 된다.
이제 원하는 디렉토리에서 poetry init으로 toml을 생성한다. 이후 터미널에서 지시하는 대로 상세정보를 입력하고(입력하지 않아도 된다.)
Package name [basic_django]:
Version [0.1.0]:
Description []:
Author [Rasul Kireev <rasul.kireev@guycarp.com>, n to skip]:
License []:
호환할 파이썬 버전을 선택한다.
Compatible Python versions [^3.11]: ^3.9
이후 개발용 의존성관리와 일반(main)의존성 관리를 따로 만들겠냐고 묻는데, 크게 상관없으나 no 라고 하고 추후 추가할 수 있다.
Would you like to define your main dependencies interactively? (yes/no) [yes] no
Would you like to define your development dependencies interactively? (yes/no) [yes] no
2. 프로젝트들을 위한 패키지 설치 및 기본 설정 변경
2-1. add
기본이 되는 Django, DRF, 토큰인증을 위한 simplejwt, CORS를 위한 django-cors-headers, secret key를 환경변수로 넘기기위한 djanog-dotenv, 편리한 api 개발을 위한 drf-yasg 를 설치한다.
poetry add django djangorestframework djangorestframework-simplejwt
poetry add django-dotenv django-cors-headers drf-yasg
add 명령어에 의해 자동으로 가상환경을 만들고 lock 파일도 형성된다.
2-2. 가상환경에서 Django 프로젝트 생성
poetry shell
django-admin.py startproject my_project .
여기까지 하면 프로젝트의 구조는 다음과 같다.
.
├── my_project
│ ├── __init__.py
│ ├── asgi.py
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
├── manage.py
├── poetry.lock
└── pyproject.toml
2-3. 원하는 app 추가
python3 manage.py startapp users
python3 manage.py startapp todolists
2-4. settings.py 설정하기
DRF관련 설정
INSTALLED_APPS = [
...
"rest_framework",
...
]
simplejwt 관련 설정
INSTALLED_APPS = [
...
"rest_framework_simplejwt",
...
]
...
REST_FRAMEWORK = {
# Use Django's standard `django.contrib.auth` permissions,
# or allow read-only access for unauthenticated users.
"DEFAULT_AUTHENTICATION_CLASSES": (
"rest_framework_simplejwt.authentication.JWTAuthentication",
),
}
...
SIMPLE_JWT = { # 공식문서에서 보고 필요한 것만 지정할 수 있다.
"ACCESS_TOKEN_LIFETIME": timedelta(minutes=60),
"REFRESH_TOKEN_LIFETIME": timedelta(days=1),
}
cors 관련 설정
INSTALLED_APPS = [
...
"corsheaders",
...
]
MIDDLEWARE = [
...
"corsheaders.middleware.CorsMiddleware",
"django.middleware.common.CommonMiddleware", # 가급적 이 미들웨어 위에 위치
...
]
CORS_ALLOWED_ORIGINS = ["http://127.0.0.1:5500"] # live server
drf-yasg 관련 설정
# settings.py
INSTALLED_APPS = [
...
"drf_yasg",
...
]
# urls.py, 공식문서 참고
...
from rest_framework import permissions
from drf_yasg.views import get_schema_view
from drf_yasg import openapi
...
schema_view = get_schema_view(
openapi.Info(
title="Snippets API",
default_version='v1',
description="Test description",
terms_of_service="https://www.google.com/policies/terms/",
contact=openapi.Contact(email="contact@snippets.local"),
license=openapi.License(name="BSD License"),
),
public=True,
permission_classes=[permissions.AllowAny],
)
urlpatterns = [
re_path(r'^swagger(?P<format>\.json|\.yaml)$', schema_view.without_ui(cache_timeout=0), name='schema-json'),
re_path(r'^swagger/$', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),
re_path(r'^redoc/$', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'),
...
]
dot-env로 secret_key 분리 설정
링크: https://spear-mans-dev.tistory.com/16
23.04.11 TIL(팀플개발일지)
오늘 한 것 팀 과제 기능 구현 팀 과제 기능 테스팅 코딩테스트 풀이 팀 과제 기능 구현: 프로필 조회 및 수정 0. 협업 환경 조성 본격적으로 시작하기 전에 협업을 위한 환경을 조성하기로 하였
spear-mans-dev.tistory.com
기타 설정
INSTALLED_APPS = [
...
"users", # 내가 정의한 app들 적용
"todolists",
]
# 시간대와 언어 설정
LANGUAGE_CODE = "ko-kr"
TIME_ZONE = "Asia/Seoul"
이렇게 프로젝트 시작을 위한 기본적인 준비를 마치었다.
배운점
poetry의 강점과 사용방법에 대해 알게 되었다.
레퍼런스
urllib.error.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer cer
import yfinance as yf msft = yf.Ticker("MSFT") msft.info I tried to print msft.info and got 'urllib.error.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify ...
stackoverflow.com
https://github.com/python-poetry/poetry/issues/507
Poetry Command Not Found on zsh · Issue #507 · python-poetry/poetry
I am on the latest Poetry version. I have searched the issues of this repo and believe that this is not a duplicate. If an exception occurs when executing a command, I executed it again in debug mo...
github.com
https://builtwithdjango.com/blog/basic-django-setup
Setting up a basic Django project with Poetry
In this tutorial, we will go through the process of setting up the most basic Django project with Poetry. We will use that as a setup up for other posts and tutorials.
builtwithdjango.com
Poetry를 사용하여 가상환경 만들기
Poetry를 사용하기 위해 다음의 공식문서를 참고하여 학습한 내용을 정리 한 글입니다.Introduction | Documentation | Poetry - Python dependency management and packaging made easy.하나의 기술을
velog.io
https://www.django-rest-framework.org/#installation
Home - Django REST framework
www.django-rest-framework.org
https://drf-yasg.readthedocs.io/en/stable/readme.html#usage
drf-yasg - Yet another Swagger generator — drf-yasg 1.20.1 documentation
Since the schema does not usually change during the lifetime of the django process, there is out of the box support for caching the schema view in-memory, with some sane defaults: caching is enabled by the cache_page decorator, using the default Django cac
drf-yasg.readthedocs.io
'TIL' 카테고리의 다른 글
23.04.28 TIL (0) | 2023.05.01 |
---|---|
23.04.26 TIL - DRF 개인과제: model, view, serializer,url (0) | 2023.04.27 |
23.04.25 TIL - defaultdict, lambda, callable (0) | 2023.04.25 |
23.04.24 TIL - DRF: serialize, renderer, response (0) | 2023.04.24 |
23.04.21 TIL (0) | 2023.04.24 |