[Project Directory]
project
Pipfile
djangoproject
djangoproject
settings.py
urls.py
api
urls.py
front
manage.py
[Install Django]
$ mkdir project
$ cd project
$ pipenv shell
(project) $ pip install django
(project) $ pip install djangorestframework
(project) $ pip install django-cors-headers
(project) $ django-admin startproject djangoprojectname
(project) $ cd djangoprojectname
(project) $ python manage.py startapp appname
Error : sqlite3 버전 오류 시 조치
---------------
sqlite 3.7 -> 3.36
cd /opt/
sudo wget https://sqlite.org/2021/sqlite-autoconf-3360000.tar.gz
sudo tar -zxf sqlite-autoconf-3360000.tar.gz
cd sqlite-autoconf-3360000/
gcc 컴파일러가 없어서
sudo yum install gcc
sudo ./configure
sudo make clean
sudo make -j 20
sudo make install
sudo /bin/cp -rf /usr/lib64/libsqlite3.so.0.8.6 /usr/lib64/libsqlite3.so.0.8.6_bak
sudo /bin/cp -rf /usr/local/lib/libsqlite3.so.0.8.6 /usr/lib64/libsqlite3.so.0.8.6
python
>>> import sqlite3
>>> sqlite3.sqlite_version
3.36.0
---------------
(project) $ python manage.py migrate
(project) $ python manage.py createsuperuser
(project) $ vi djangoproject/settings.py
impor os
ALLOWED_HOSTS = ['*']
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework', # Rest Framework
'corsheaders', # CORS
'api', # api
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'corsheaders.middleware.CorsMiddleware', # CORS
]
CORS_ORIGIN_ALLOW_ALL = True # CORS - If this is used then `CORS_ORIGIN_WHITELIST` will not have any effect
CORS_ALLOW_CREDENTIALS = True # CORS
CORS_ORIGIN_WHITELIST = [
"http://localhost:8000",
"http://localhost:3000",
] # CORS - If this is used, then not need to use `CORS_ORIGIN_ALLOW_ALL = True`
CORS_ORIGIN_REGEX_WHITELIST = [] # CORS
LANGUAGE_CODE = 'ko'
TIME_ZONE = 'Asia/Seoul'
(project) $ python manage.py runserver 0.0.0.0:8000
connect to http://localhost:8000
browser -> 80 -> 8000 라우팅 필요 (아마존 특성)
[Add routing from 80 to 8080]
AWS는 80포트외에 다른 포트를 오픈하지 않으므로 80포트를 8080포트로 리다이렉트가 필요하다.
8080이 아닌 다른 포트로도 라우팅 가능.
sudo iptables -A PREROUTING -t nat -i eth0 -p tcp --dport 80 -j REDIRECT --to-port 8000
[Add startup script in booting]
sudo vi /etc/rc.local
add following code
---
#!/bin/sh
sudo iptables -A PREROUTING -t nat -i eth0 -p tcp --dport 80 -j REDIRECT --to-port 8000
---
sudo chmod 755 /etc/rc.local
system rebooting
[List routing information]
sudo iptables -t nat -L --line-numbers
[Delete routing item]
sudo iptables -t nat -D PREROUTING 1
[List Port usage]
netstat -ntlp
[Install React]
(project) $ create-react-app front
(project) $ cd front
(project) $ yarn start (default port 3000)
(project) $ PORT=3009 yarn start (명령어로 포트 변경)
시작포트를 자동으로 변경하기
package.json
"scripts": {
"start": "export PORT=3009 && react-scripts start",
[Connect React to Django]
(project) $ cd ..
(project) $ vi djangoproject/settings.py
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
os.path.join(BASE_DIR, 'front', 'build'), # REACT index.html Path
],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
STATICFILES_DIRS = [ # REACT Static Path
os.path.join(BASE_DIR, 'front', 'build', 'static'),
]
(project) $ vi manage.py (리액트 빌드 후 실행되도록 변경)
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ds.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
try:
if sys.argv[3] == 'react':
project_root = os.getcwd()
os.chdir(os.path.join(project_root, "front"))
os.system("npm run build")
os.chdir(project_root)
sys.argv.pop(3)
except IndexError:
execute_from_command_line(sys.argv)
else:
execute_from_command_line(sys.argv)
# execute_from_command_line(sys.argv)
if __name__ == '__main__':
main()
(project) $ vi djangoproject/urls.py
from django.contrib import admin
from django.urls import path, include, re_path
from django.views.generic import TemplateView
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include('api.urls')),
path('', TemplateView.as_view(template_name='index.html')), # React template index.html
]
(project) $ vi djangoproject/api/urls.py
from django.urls import include, path
from rest_framework import routers
from django.views.decorators.csrf import csrf_exempt
from django.views.generic import TemplateView
from . import views
router = routers.DefaultRouter()
# router.register(r'integrations', views.IntegrationViewSet, basename='integration')
urlpatterns = [
path('', include(router.urls)),
# path('swagger<str:format>', yasg.schema_view.without_ui(cache_timeout=0), name='schema-json'),
# path('swagger/', yasg.schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),
# path('docs/', yasg.schema_view.with_ui('redoc', cache_timeout=0), name='schema-redic'),
# path('api_token_auth/', views.ApiAuthToken.as_view()),
]
(project) $ python manage.py runserver 0.0.0.0:8000 react
리액트를 빌드하고 장고서버 실행하여 아래 URL 접속 시 바로 빌드된 리액트 실행됨
HTTP://localhost:8000
[React 라이브러리 설치]
yarn add react-router-dom
yarn add antd
yarn add axios
yarn add xlsx
댓글
댓글 쓰기