Django + React Build

김회민·2022년 4월 18일
0

2022년 4월 17일 일요일.
React Project를 Django와 연동하기 위해 삽질한 끝에 해결했다.

목표

# [ React Path ]
/home/project/js/sagi-front/

# [ Django Path ]
/home/project/python/sagi-back/

React Path에서 yarn build를 해서 나온 index.html과 static file들을 Django home 에 뿌려주는 것이 오늘의 목표였다.

Debug = False 일때!!!!!!

문제

Debug = True 일 때는 정상적으로 static 파일이 불러와지지만, False일때는 html 파일을 제외한 다른 모든 파일이 불러와지지 않았다.

해결법

React 설정

# [React Path]/package.json
{
    // ...
    "homepage": "assets/web/"
    // ...
    "scripts": {
        "build": "BUILD_PATH='[Django Path]/build' react-scripts build"
    }
}
# Bash
> yarn build
> npm run build
# 파일 이동
[Django Path]/build/index.html
=> [Django Path]/template/index.html

Django 설정

# [Django Path]/mysite/settings.py

# Templates
TEMPLATES = [
    {
        # ...
        'DIRS': [
            os.path.join(BASE_DIR, 'template')
        ],
        # ...
    },
]

# Static files (CSS, JavaScript, Images)
STATIC_ROOT = BASE_DIR / 'staticfiles'
STATIC_URL = '/assets/'
STATICFILES_DIRS = [
    ( 'web', os.path.join( BASE_DIR, 'build' ) ),
]
# Bash
> python manage.py collectstatic
# [Django Path]/mysite/urls.py
from django.conf import settings
from django.conf.urls.static import static

from django.contrib import admin
from django.urls import path, re_path

from django.views.generic import TemplateView
from django.views.static import serve

urlpatterns = [
    path('admin/', admin.site.urls),
    re_path(r'^assets/(?P<path>.*)$', serve, { 'document_root': settings.STATIC_ROOT }),
    re_path(r'.*', TemplateView.as_view(template_name = 'index.html'), name="react-web"),
]

urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

개념 정리

STATIC_URL

# [Django Path]/mysite/settings.py
STATIC_URL =/assets/

웹페이지에서 사용할 정적 파일의 최상위 URL

문자열은 반드시 ‘/’로 끝나야 함.

위와 같이 설정한 경우, 웹페이지에서 static 파일을 불러올 때 /assets/... 로 불러올 수 있음.

STATICFILES_DIRS

# [Django Path]/mysite/settings.py
STATICFILES_DIRS = [
    ( 'web', os.path.join( BASE_DIR, 'build' ) ),
]

개발단계( DEBUG Mode )에서 사용하는 정적 파일 경로

여러 경로를 지정할 수 있고, list나 tuple로 담으면 된다.

접두사를 붙이면 ( 위의 경우 ‘web’ ) 파일을 불러올 때 /STATIC_URL/web/... 로 불러올 수 있음.

STATIC_ROOT

# [Django Path]/mysite/settings.py
STATIC_ROOT = BASE_DIR / 'staticfiles'

Django 프로젝트에서 사용하는 모든 정적 파일을 한 곳에 모아놓은 경로.

개발단계에서는 적용되지 않으며, 실 서비스 환경에서 사용된다.

# Bash
> python manage.py collectstatic

이 명령어를 입력하면 STATIC_ROOT에 지정된 폴더에 static file을 넣는다.

SERVE View

# [Django Path]/mysite/urls.py
from django.conf import settings
from django.urls import re_path
from django.views.static import serve

urlpatterns = [
    re_path(r'^assets/(?P<path>.*)$', serve, { 'document_root': settings.STATIC_ROOT }),
]

serve view 함수

서버에 위치한 파일을 읽어서 - open(fullpath, ‘rb’)

스트리밍 방식으로 응답한다. - StreamingHttpResponse

단점은, 웹서버가 직접 서빙하는 것보다 성능이 떨어진다.

참고 사이트

https://gaussian37.github.io/python-django-non-debug-mode/
https://blog.hannal.com/2015/04/start_with_django_webframework_06/

profile
백엔드 개발자 지망생

0개의 댓글