😆

AWS cloud 9 실습

0. 세팅 영상

Video preview

1. AWS 가입 & 신용카드 등록

AWS 가입한 후 신용카드 등록을 합니다.
notion imagenotion image

2. cloud9 접속 및 환경 세팅

서비스 > 개발자 도구 > cloud9 클릭합니다.
notion imagenotion image
 
AWS Cloud9은 브라우저만으로 코드를 작성, 실행 및 디버깅할 수 있는 클라우드 기반 IDE(통합 개발 환경)입니다. cloud9 자체는 무료이며, 같이 사용되는 ec2나 리소스의 비용은 부과됩니다.
notion imagenotion image
 
AWS 콘솔에서 서비스 > cloud9 > Create environment 를 누릅니다.
notion imagenotion image
notion imagenotion image
notion imagenotion image
 
환경만들기를 클릭합니다.
notion imagenotion image
notion imagenotion image
 
네트워크 환경 설정은 인스턴스 타입만 t3.small로 설정하고 나머지는 그대로 하도록 합니다.
다음단계를 클릭해주세요.
notion imagenotion image
 
검토 부분에서도 다음단계를 클릭해주세요.
notion imagenotion image
 
환경생성중입니다.
참고로 새 ec2가 생성되며, 그 ec2에 연결되어 개발환경이 제공됩니다.
notion imagenotion image
 
환경 설정이 끝났습니다.
notion imagenotion image
 
  • 영상에서 자주 쓸 단축키
    • Alt + Shift + 화살표 위 : 위에다 붙여넣기 Ctrl + D : 한 줄 삭제 Ctrl + C : 서버 중단
 
아래 터미널에서 ls를 쳐서 파일 목록을 보도록 하겠습니다.
$ ls
 
README.md파일을 열어보도록 하겠습니다.
$ cat README.md
notion imagenotion image
 
+(플러스) 버튼을 클릭하면 파일을 추가할 수 있습니다.
notion imagenotion image
notion imagenotion image
 
ctrl+s를 눌러 파일을 저장합니다.
notion imagenotion image
 

1. python

001.py라고 저장하도록 하겠습니다.
notion imagenotion image
 
hello를 출력해보도록 하겠습니다. 아래의 코드를 입력한 후 저장합니다.
print('hello')
 
Run 버튼을 누르면 명령어가 출력되는 것을 볼 수 있습니다.
notion imagenotion image
 

2. html

마찬가지로 html 파일도 작성합니다. html 파일은 !(느낌표)를 입력한 뒤 Tab을 누르면 html 기본 형태가 완성됩니다. h1입력 후 Tab을 누르면 자동 완성이 됩니다.
notion imagenotion image
 
이렇게 AWS Cloud9는 Emmet문법도 지원하는 것을 알 수 있습니다.
 
Preview > Preview File 001.html을 클릭하면 html 파일 미리보기가 가능합니다.
notion imagenotion image
 
옆에서 보면서 바로바로 고칠 수 있는 장점이 있습니다.
notion imagenotion image
 
html을 수정한 후 새로고침 버튼을 클릭하면 수정된 내용이 반영된 화면을 볼 수 있습니다.
notion imagenotion image
 

3. git

Git도 설치 없이 바로 사용 가능합니다.
$ git init $ git remote add origin <git주소> $ git pull origin main
 

4. Django

우선 작업할 mysite 디렉토리를 생성한 후 폴더 안으로 들어갑니다.
$ mkdir mysite $ cd mysite
 
가상환경을 생성한 후 가상환경 속으로 들어갑니다.
$ python -m venv venv $ source venv/bin/activate $ ls
 
가상환경 밖으로 나오고 싶을때는 아래의 명령어를 적습니다.(실습은 하지 않습니다.)
deactivate
💡
가상환경 밖으로 나오신 경우에는 반드시 가상환경 속에서 작업해 주시길 바랍니다.
 
가상환경 속에서 작성하는 명령어 앞에는 (venv)를 붙이도록 하겠습니다.
Django를 3.2 버전으로 만들도록 합니다.
$ (venv) pip install django==3.2
 
장고 프로젝트를 생성합니다.
$ (venv) django-admin startproject tutorialdjango .
 
22년 11월 migrate를 해주기 전 sqlite3 버전 업데이트가 필수가 되었습니다. 아래 명령어를 한 번에 복사해 버전업데이트를 진행해주세요.
notion imagenotion image
sudo wget https://sqlite.org/2022/sqlite-autoconf-3400000.tar.gz sudo tar -zxf sqlite-autoconf-3400000.tar.gz cd sqlite-autoconf-3400000/ sudo ./configure sudo make clean && sudo make -j 20 && sudo make install sudo cp -rf /usr/lib64/libsqlite3.so.0.8.6 /usr/lib64/libsqlite3.so.0.8.6_bak sudo cp -rf /usr/local/lib/libsqlite3.so.0.8.6 /usr/lib64/libsqlite3.so.0.8.6 sqlite3 --version
(백업) sqlite3 버전 업그레이드 하는 방법 - 참고하지 않으셔도 됩니다.
  1. sqlite3 최신 버전 다운로드 및 설치
    1. $ (venv) wget https://www.sqlite.org/2020/sqlite-autoconf-3310100.tar.gz $ (venv) yum -y install gcc $ (venv) tar zxvf sqlite-autoconf-3310100.tar.gz $ (venv) cd sqlite-autoconf-3310100 $ (venv) ./configure --prefix=/usr/local $ (venv) make $ (venv) sudo make install
  1. 컴파일 후 시스템 링크 라이브러리에 반영
    1. $ (venv) sudo sh -c "echo '/usr/local/lib' >> /etc/ld.so.conf" $ (venv) sudo /sbin/ldconfig
  1. 설치한 sqlite3 반영
    1. $ (venv) vi .bashrc $ (venv) source .bashrc
  1. migrate
    1. $ (venv) cd ../ $ (venv) python manage.py migrate
       
 
migrate를 시켜줍니다. mysite 폴더에서 해야 하므로 한 칸 위로 올라갑니다.
$ (venv) cd .. $ (venv) python manage.py migrate
 
서버를 실행시킵니다.
python manage.py runserver 8080
 
django프로젝트는 8080포트를 통해 서버를 실행시킬 수 있다고 뜨며, 작성한 코드는 빨간색 박스 링크로 들어가면 볼 수 있다고 뜹니다.
notion imagenotion image
 
아직은 접속이 안되실거에요. 아래 세팅 변경을 통해 세팅을 해주세요.
ALLOWED_HOSTS = ['*']
/mysite/tutorialdjango/settings.py 28번째 라인
 
저장하시고 링크로 들어가면 로켓모양이 보이는 것을 볼 수 있습니다.
notion imagenotion image

3. Django URL과 template tag

  • 아래 실습 영상을 참고해주세요.
    • Video preview
로켓 모양 후 사용한 모든 코드
python manage.py startapp main settings.py로 들어가서 33번째 줄 INSTALLED_APPS = [ 'main', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] url 설계 / -> home화면(index) /about -> about화면(about) /product -> product화면(product) /contact -> contact화면(contact) urls.py from django.contrib import admin from django.urls import path from main.views import index, about, product, contact urlpatterns = [ path('admin/', admin.site.urls), path('', index), path('about/', about), path('product/', product), path('contact/', contact), ] main/views.py from django.shortcuts import render def index(request): return render(request, 'index.html') def about(request): return render(request, 'about.html') def product(request): return render(request, 'product.html') def contact(request): return render(request, 'contact.html') # 2시 4분까지 쉬겠습니다. # 참고 : touch {about,index,product,contact}.html # 클릭해서 main/templates/about.html 등 4개를 만들어주세요. # 각각의 파일에는 <h1>hello 파일이름</h1> /mysite$ python manage.py runserver 8080 # 과제 url 설계 a/ -> a화면 b/ -> b화면 c/ -> c화면 1. tutorialdjango/urls.py 2. main/views.py 파일 수정 3. main/templates 안에 해당 html 파일 생성(내용 작성까지) --- 과제 코드 --- urls.py from django.contrib import admin from django.urls import path from main.views import index, about, product, contact, a, b, c urlpatterns = [ path('admin/', admin.site.urls), path('', index), path('about/', about), path('product/', product), path('contact/', contact), path('a/', a), path('b/', b), path('c/', c), ] views.py from django.shortcuts import render def index(request): return render(request, 'index.html') def about(request): return render(request, 'about.html') def product(request): return render(request, 'product.html') def contact(request): return render(request, 'contact.html') def a(request): return render(request, 'aaa.html') def b(request): return render(request, 'bbb.html') def c(request): return render(request, 'ccc.html') /templates 폴더 안에는 aaa.html, bbb.html, ccc.html가 있어야 합니다. ########## https://docs.djangoproject.com/en/4.1/ref/templates/builtins/ ########## pandas의 DataFrame과 python의 dict를 사용한 데이터 출력 (template tag 사용) from django.shortcuts import render # pip install pandas # pip install lxml import pandas as pd def index(request): data = [{ 'title': 'title1', 'contents': 'contents1', 'date': '2022-11-19' }, { 'title': 'title2', 'contents': 'contents2', 'date': '2022-11-19' }, { 'title': 'title3', 'contents': 'contents3', 'date': '2022-11-19' }] context = { 'notice_data': data } return render(request, 'index.html', context) def about(request): data = pd.read_html('https://ko.wikipedia.org/wiki/%EB%8C%80%ED%95%9C%EB%AF%BC%EA%B5%AD%EC%9D%98_%EC%9D%B8%EA%B5%AC') context = { 'population_data': data[4] } return render(request, 'about.html', context) def product(request): return render(request, 'product.html') def contact(request): return render(request, 'contact.html') def a(request): return render(request, 'aaa.html') def b(request): return render(request, 'bbb.html') def c(request): return render(request, 'ccc.html') <h1>hello about</h1> {% for i in population_data %} <p>{{i}}</p> {% endfor %} ########## 연도 (년) 추계인구(명) 출생자수(명) 사망자수(명) 자연증가수(명) 조출생률 (1000명당) 조사망률 (1000명당) 자연증가율 (1000명당) 합계출산율 ########### from django.shortcuts import render # pip install pandas # pip install lxml import pandas as pd def index(request): data = [{ 'title': 'title1', 'contents': 'contents1', 'date': '2022-11-19' }, { 'title': 'title2', 'contents': 'contents2', 'date': '2022-11-19' }, { 'title': 'title3', 'contents': 'contents3', 'date': '2022-11-19' }] context = { 'notice_data': data } return render(request, 'index.html', context) def about(request): data = pd.read_html('https://ko.wikipedia.org/wiki/%EB%8C%80%ED%95%9C%EB%AF%BC%EA%B5%AD%EC%9D%98_%EC%9D%B8%EA%B5%AC') context = { 'population_data': data[4].values.tolist() } return render(request, 'about.html', context) def product(request): return render(request, 'product.html') def contact(request): return render(request, 'contact.html') def a(request): return render(request, 'aaa.html') def b(request): return render(request, 'bbb.html') def c(request): return render(request, 'ccc.html') ############## <h1>hello about</h1> <table> <tr> <th>연도 (년)</th> <th>추계인구(명)</th> <th>출생자수(명)</th> <th>사망자수(명)</th> </tr> {% for i in population_data %} <tr> <td>{{i.0}}</td> <td>{{i.1}}</td> <td>{{i.2}}</td> <td>{{i.3}}</td> </tr> {% endfor %} </table> ############ https://docs.djangoproject.com/en/3.2/ref/models/fields/ #### python manage.py makemigrations python manage.py migrate #admin.py from django.contrib import admin from .models import Notice admin.site.register(Notice) python manage.py createsuperuser username : leehojun email : leehojun@gmail pw : 이호준33@@ python manage.py runserver 8080 게시물 3개 만들어주세요. from django.db import models class Notice(models.Model): title = models.CharField(max_length=50) contents = models.TextField() date = models.DateTimeField() def __str__(self): return self.title + ' ' + self.contents[:10] + '...' <h1>hello product</h1> {% for i in data %} <p>{{i.title}}</p> <p>{{i.contents}}</p> <p>{{i.date}}</p> {% endfor %}

4. Django + Bootstrap Blog 만들기

블로그 만들기 코드
외부에 있는 UI 템플릿 다양한 선택지 - Django + tailwind : 모놀리식으로 추천 - Django + Bootstrap - Django + Vue : 마이크로식으로 추천 (인원수가 적게 필요) - Django + React : 마이크로식으로 개발하려면 인원수가 좀 많이 필요 $ mkdir mysite $ cd mysite $ python -m venv venv $ source venv/bin/activate $ (venv) pip install django==3.2 $ (venv) django-admin startproject tutorialdjango . settings.py -> 28번째 줄 ALLOWED_HOSTS = ['*'] 터미널에 아래 코드를 붙여넣으세요. sudo wget https://sqlite.org/2022/sqlite-autoconf-3400000.tar.gz sudo tar -zxf sqlite-autoconf-3400000.tar.gz cd sqlite-autoconf-3400000/ sudo ./configure sudo make clean && sudo make -j 20 && sudo make install sudo cp -rf /usr/lib64/libsqlite3.so.0.8.6 /usr/lib64/libsqlite3.so.0.8.6_bak sudo cp -rf /usr/local/lib/libsqlite3.so.0.8.6 /usr/lib64/libsqlite3.so.0.8.6 sqlite3 --version 엔터 한 번 치시고 시작하세요. $ (venv) cd .. $ (venv) python manage.py migrate python manage.py startapp main settings.py로 들어가서 33번째 줄 INSTALLED_APPS = [ 'main', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] url 설계 / /blog /blogdetails # urls.py 파일 from django.contrib import admin from django.urls import path from main.views import index, blog, blogdetails urlpatterns = [ path('admin/', admin.site.urls), path('', index), path('blog/', blog), path('blogdetails/', blogdetails), ] # views.py 파일 from django.shortcuts import render def index(request): return render(request, 'index.html') def blog(request): return render(request, 'blog.html') def blogdetails(request): return render(request, 'blogdetails.html') # 이제 각각 html 파일을 만듭니다. (venv) environment/mysite $ cd main (venv) environment/mysite/main $ mkdir templates (venv) environment/mysite/main $ cd templates/ (venv) environment/mysite/main/templates $ touch {index,blog,blogdetails}.html # 각각 파일에 파일명으로 text를 입력한 후 아래 명령어를 실행합니다. (venv) environment/mysite/main/templates $ cd .. (venv) environment/mysite/main $ cd .. (venv) environment/mysite $ python manage.py runserver 8080 https://startbootstrap.com/theme/clean-blog 에서 파일을 다운로드 받습니다. post.html -> blogdetails.html index.html 복사 -> 복사한 파일을 blog.html mysite > static이라는 폴더 생성 static 폴더 안에 파일 모두 업로드 업로드 한 파일 중 .html파일은 templates로 이동 settings.py 파일 안에 121번째 줄을 아래와 같이 추가 STATIC_URL = '/static/' STATICFILES_DIRS = [ BASE_DIR / 'static', ] 각각의 html 파일에 최상단에 아래 코드를 붙여 넣습니다. {% load static %} 불러오는 양식은 아래와 같은 형태로 변경을 하셔야 합니다. <img src="{% static 'jeju.jpg' %}"> google에 django blog models github에 django blog models https://github.com/devmahmud/DjangoBlog/blob/master/blog/models.py https://djangocentral.com/building-a-blog-application-with-django/ # urls.py파일 수정 from django.contrib import admin from django.urls import path from main.views import index, blog, blogdetails urlpatterns = [ path('admin/', admin.site.urls), path('', index), path('blog/', blog), path('blogdetails/<int:post_id>', blogdetails), ] # models.py 추가 from django.db import models class Post(models.Model): title = models.CharField(max_length = 200, unique = True) content = models.TextField() updated_on = models.DateTimeField(auto_now = True) created_on = models.DateTimeField(auto_now_add = True) def __str__(self): return self.title # 터미널창 (venv) environment/mysite $ python manage.py makemigrations (venv) environment/mysite $ python manage.py migrate # 어드민 사이트 등록 from django.contrib import admin from .models import Post admin.site.register(Post) # 어드민 유저 생성 python manage.py createsuperuser python manage.py runserver 8080 /admin으로 접속 게시물 3개 생성 # views.py 수정 from django.shortcuts import render from .models import Post def index(request): return render(request, 'index.html') def blog(request): posts = Post.objects.all() return render(request, 'blog.html', {'posts':posts}) def blogdetails(request, post_id): post = Post.objects.get(pk=post_id) return render(request, 'blogdetails.html', {'post':post}) # 블로그 페이지 수정 {% for item in posts %} <!-- Post preview--> <div class="post-preview"> <a href="post.html"> <h2 class="post-title">{{item.title}}</h2> <h3 class="post-subtitle">{{item.contnets}}</h3> </a> <p class="post-meta"> Posted by <a href="#!">Start Bootstrap</a> {{item.updated_on}} </p> </div> <!-- Divider--> <hr class="my-4" /> {% endfor %} # 위와 같이 반복되는 내용을 수정해주세요. # blogdetails에도 아래와 같이 수정 <div class="post-heading"> <h1>{{post.title}}</h1> <h2 class="subheading">{{post.content}}</h2> <span class="meta"> Posted by <a href="#!">Start Bootstrap</a> on August 24, 2022 </span> </div> --- # a 태그에서 사용하기 위해 name필드 설정 from django.contrib import admin from django.urls import path from main.views import index, blog, blogdetails urlpatterns = [ path('admin/', admin.site.urls), path('', index, name='index'), path('blog/', blog, name='blog'), path('blogdetails/<int:post_id>', blogdetails, name='blogdetails'), ] {% url 'some-url-name' v1 v2 %} {% url 'some-url-name' arg1=v1 arg2=v2 %} # blog.html을 아래와 같이 수정합니다. <p>{% url 'index' %}</p> <p>{% url 'blog' %}</p> {% for item in posts %} <p>{% url 'blogdetails' item.pk %}</p> <!-- Post preview--> <div class="post-preview"> <a href="/blogdetails/{{ item.pk }}"> <h2 class="post-title">{{item.title}}</h2> <h3 class="post-subtitle">{{item.contnet}}</h3> </a> <p class="post-meta"> Posted by <a href="#!">Start Bootstrap</a> {{item.updated_on}} </p> </div> <!-- Divider--> <hr class="my-4" /> {% endfor %} --- 우리가 하지 않은 것 form 회원가입 db 1:1 1:다 -> 뎃글 다:다