PostgreSQL 다운
Django
파이썬 설치 후 환경 변수 세팅
프로젝트 관리할 빈 폴더 생성
생성 후 가상환경 세팅
python -m venv myvenv
cd myvenv
Scripts\\activate.bat 실행 ## 실행이 안될경우 cmd에서
pip install django
pip install djangorestframework
--pip install django-rest-swagger
project 및 APP 생성
cd ../ (가상환경 디렉터리 나오기)
django-admin startproject [mydjango] . --프로젝트 이름
python manage.py startapp [api] --앱 이름
데이터 베이스 연결 (settings.py)
pip install psycopg2 # python에서 사용되는 PostgreSQL DB의 어댑터
pip install django-environ ## DB 설정 정보 등 따로 관리
.env(project 디렉터리 안에 생성)
DB_NAME=postgres
DB_USER=root
DB_PASSWORD=1234
DB_HOST=localhost
DB_PORT=5432
Secret key 설정
secrets.json 생성
{
"SECRET_KEY" : "시크릿 키"
}
settings.py 설정
# secret key 설정
from django.core.exceptions import ImproperlyConfigured
import os, json
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# json 파일 위치 설정
secret_file = os.path.join(BASE_DIR, 'secrets.json')
# json 파일 열기
with open(secret_file) as f:
secrets = json.loads(f.read())
def get_secret(setting):
# 비밀 변수를 가져오거나 명시적 예외 반환
try:
return secrets[setting]
except KeyError:
error_msg = "Set the {} environment varialbe".format(setting)
raise ImproperlyConfigured(error_msg)
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = get_secret("SECRET_KEY")
그 외 settings.py
import environ
env = environ.Env()
environ.Env.read_env()
DATABASES = {
'default' : {
'ENGINE' : 'django.db.backends.postgresql',
'NAME' : env.str("DB_NAME"),
'USER' : env.str("DB_USER"),
'PASSWORD' : env.str("DB_PASSWORD"),
'HOST' : env.str("DB_HOST"),
'PORT' : env.str("DB_PORT"),
}
}
LANGUAGE_CODE = 'ko'
TIME_ZONE = 'Asia/Seoul'
USE_I18N = True
USE_TZ = True
postgre 설정
create user root with password 'password';
alter role root set client_encoding to 'utf-8';
alter role root set timezone to 'Asia/Seoul';
grant all privileges on database [databasename] to root;
접속 확인
python manage.py makemigrations ##모델등이 변경될 때만
python manage.py migrate
---> 해당 문구 나오면 연동 성공
Operations to perform:
Apply all migrations: admin, auth, contenttypes, sessions
python manage.py runserver
asgiref 3.7.2
Django 5.0.3
django-environ 0.11.2 --환경변수 설정 및 사용
djangorestframework 3.14.0 -- api로 사용
pip 24.0
psycopg2 2.9.9
pytz 2024.1
setuptools 65.5.0
sqlparse 0.4.4
tzdata 2024.1