aws

python django for aws ec2

clarus fluvius 2023. 1. 2. 16:50

python django 

2022.12.29 내 포트폴리오 AWS에 올려보기, Django, Nginx, AWS, EC2, Route53, Docker

https://www.youtube.com/watch?v=IBC95cJnbRQ

*. Pycharm Terminal Setting: Git bash : 파이참 터미널 설정 변경 방법은 "pythonpycharm.txt" 참조.

0. 먼저 무료 템플릿 다운로드 및 압축 풀기: https://startbootstrap.com/theme/freelancer

    assets

    css

    js

    index.html

1. Pycharm/New Project/Left Menu: Django

   *****: 여기서 2가지를 주의해야 하는데,

    1) 프로젝트 폴더명이 이미 존재하면, 반드시 사전에 해당 폴더를 삭제해 주어야 하는 것과

    2) 상단 "Project" 이름과 "venv" 이름에서, 아래와 같이 프로젝트 이름 뒷면에 반드시 "\venv"가 추가되어 있어야 한다.

       Project Location: G:\Python\Workspace\portfolio2023

       venv Location:    G:\Python\Workspace\portfolio2023\venv

    ===> 프로젝트 생성 후 폴더 및 파일 상태 확인

    portfolio2023

        portfolio2023

        templates

        venv

        External Libraries

        Scratches and Consoles

2. 준비된 index.html 파일은 "templates" 폴더에 넣고,

   준비된 "assets", "css", "js" 폴더는, 새로 "static" 폴더를 만들어 그 안에 넣는다.

 

3. 패키지 라이브러리 "djangorestframework" 설치

   $ pip install djangorestframework

 

4. 앱 생성: $ python manage.py startapp webpage

   혹시라도 아래와 같은 에러가 발생하면, "settings.py" 파일 상단에 "import os" 추가해 준다.

   File "G:\Python\Workspace\portfolio2023\portfolio2023\settings.py", line 57, in <module>

    'DIRS': [os.path.join(BASE_DIR, 'templates')]

   NameError: name 'os' is not defined

 

****: 여기서 부터는 실제 프로그래밍...

1. webpage/views.py

from django.shortcuts import render

from rest_framework.views import APIView

 

class Main(APIView):

    def get(self, request):

        return render(request, "index.html")

 

2. portfolio2023/urls.py

from django.conf.urls.static import static

from django.contrib import admin

from django.urls import path

 

from portfolio2023 import settings

from webpage.views import Main

 

urlpatterns = [

    path('admin/', admin.site.urls),

    path('', Main.as_view()),

]

 

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

 

project.app.settings.py 파일 수정.

"ALLOWED_HOSTS=[]" 여기를 "ALLOWED_HOSTS=["*"]로 변경하면 해결된다.

 

3. 서버 실행 및 path 확인

$ python manage.py runserver

크롬 브라우저 path 확인

http://127.0.0.1:8000/static/assets/img/portfolio_title.jpg

 

4. portfolio2023/templates/index.html 파일 수정 :

assets/~ => static/assets/~

css/~ => static/css/~

js/~ => static/js/~

 

5. pip freeze > requirements.txt

asgiref==3.6.0

Django==3.2.16

djangorestframework==3.14.0

pytz==2022.7

sqlparse==0.4.3

typing_extensions==4.4.0

****:

     requirements.txt 파일을 열고, "asgiref, typing_extensions" 이상 2개 패키지는,

     "AWS.UBUNTU 18.04" 버전에 깔린 파이썬 버전이, "Python 3.6" 버전인데,

     "Python 3.6" 버전에서는 상기 2개 파일의 버전이 맞지 않아 "에러"가 발생한다.

     그러므로 상기 2개 파일의 버전 부분을 지워주면, "AWS.UBUNTU"가 알아서 적절한 버전을 설치한다.

        asgiref

        Django==3.2.16

        djangorestframework==3.14.0

        pytz==2022.7

        sqlparse==0.4.3

        typing_extensions

 

 

*. github 연동

1. github.com.rwknag2023.repository.portfolio2023 생성

2. repository.리파지토리 생성 하자마자 나오는 아래 안내문 "복사 아이콘"을 클릭하여,

    Quick setup — if you’ve done this kind of thing before

    or

    https://github.com/rwkang2023/portfolio2023.git

    Get started by creating a new file or uploading an existing file. We recommend every repository include a README, LICENSE, and .gitignore.

    …or create a new repository on the command line

3. pycharm.파이참 terminal.터미널을 열고, 아래 내용을 "붙혀넣기" 하고, 마지막 라인에서 "엔터"하면, 모두 실행한다.

   "README.md" 파일 1개만 자동으로 "github.rwkang2023.portfolio2023" repository에 올려준다.

echo "# portfolio2023" >> README.md

git init

git add README.md

git commit -m "first commit"

git branch -M main

git remote add origin https://github.com/rwkang2023/portfolio2023.git

git push -u origin main

 

4. 현재 상태 확인...

git status

 

5. project folder.portfolio2023/.gitignore 파일 생성...

venv/*

__pycache__/*

db.sqlite3

.idea/*

 

6. git 정리

git add .   : "." 이 있음에 주의...

===> 여기서 아래 에러가 발생하면, 아래와 같은 명령으로 해결한다.

    에러 내용...

    warning: LF will be replaced by CRLF in static/assets/img/avataaars.svg.

    The file will have its original line endings in your working directory

    warning: LF will be replaced by CRLF in static/css/styles.css.

    The file will have its original line endings in your working directory

    warning: LF will be replaced by CRLF in static/js/scripts.js.

    The file will have its original line endings in your working directory

    warning: LF will be replaced by CRLF in templates/index.html.

    The file will have its original line endings in your working directory

    원인...

    LF(Line-Feed)

    Mac, Linux (Unix 계열) 줄바꿈 문자열 = \n

    ASCII 코드 = 10

    커서 위치는 그대로 두고 종이의 한라인 위로 올리는 동작

    현재 위치에서 바로 아래로 이동

    종이를 한칸올리기

    CR(Carriage-Return)

    Mac 초기 모델 줄바꿈 문자열 = \r

    ASCII 코드 = 13

    커서 위치를 맨앞으로 옮기는 동작

    커서 위치를 앞으로 이동

    CRLF (Carriage-Return+Line-Feed)

    Windows, DOS 줄바꿈 문자열 = \r\n

    CR(\r) + LR(\n) 두 동작을 합쳐서 (\r\n)

    커서를 다음라인 맨앞으로 옮겨주는 동작

해결 방안...

****: git config --global core.autocrlf true

 

gitmoji -c

 

git push

 

*. aws.ec2.ubuntu 18.04 연동

1. 최초 무조건 실행 명령...

ubuntu@ip-172-31-47-xxx:~$ sudo apt-get update

 

2. 최초 1번만 git clone https://github.com/rwkang2023/portfolio2023.git

특히 폴더 주의: "ubuntu@ip-172-31-47-xxx:~/portfolio2023" 여기 아니고,

"ubuntu@ip-172-31-47-xxx:~$" 여기임에 특히 주의...

, 프로젝트 폴더 "portfolio2023"를 절대 "성성하지 말고", "ubuntu" 루트 폴더에서 바로 "git clone" 실행할 것...

****:

 ubuntu@ip-172-31-47-xxx:~$ git clone https://github.com/rwkang2023/portfolio2023.git

 두번째부터는... "git pull" ... , 반드시 "프로젝트 폴더"에서 실행...

 ubuntu@ip-172-31-47-xxx:~/portfolio2023$ git pull

 

3. "AWS.UBUNTU 18.04"에서는 반드시 "python3" "pip3" 명령어를 사용해야 한다.

****:

 ubuntu@ip-172-31-47-xxx:~$ sudo apt install python3-pip

   ===> 여기서 주의할 것: "python-pip" 아니고, "python-pip3"도 아니고, "python3-pip3"도 아님.

 ubuntu@ip-172-31-47-xxx:~$ ls -rlt: 폴더 내용 확인

 ubuntu@ip-172-31-47-xxx:~$ python3: python3 설치 및 실행 확인

 ubuntu@ip-172-31-47-xxx:~$ pip3: pip3 설치 및 실행 확인.

 

4. requirements.txt 파일로 패키지 일괄 설치...

****:

 이상 3개 명령 모두 정상 실행되면 아래 명령으로 "requirements.txt" 파일의 "패키지" 파일을 한방에 설치한다.

 ubuntu@ip-172-31-47-xxx:~$ cd portfolio2023

 ubuntu@ip-172-31-47-xxx:~/portfolio2023$ pip3 install -r requirements.txt

    ===> 모든 "패키지" 설치가 완료되면, 비로소 아래와 같이 서버를 실행해 본다.

 ubuntu@ip-172-31-47-xxx:~/portfolio2023$ python3 manage.py runserver 0.0.0.0:8000

    ===> 위 명령 실행으로 "AWS.UBUNTU" 서버를 실행하고,

    브라우저에서 "18.222.xxx.xxx:8000"으로 확인하면, 아래와 같은 에러가 발생한다.

****:

 DisallowedHost at /

 Invalid HTTP_HOST header: '18.xxx.xxx.xxx:8000'. You may need to add '18.xxx.xxx.xxx' to ALLOWED_HOSTS.

 ===> 이것은 project.app.settings.py 파일의 "ALLOWED_HOSTS=[]" 여기를 "ALLOWED_HOSTS=["*"]로 변경하면 해결된다.

      다시 브라우저에서 "18.xxx.xxx.xxx:8000"으로 확인하면, 정상적으로 실행되는 것을 확인할 수 있다.