일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 | 9 | 10 | 11 | 12 | 13 | 14 |
15 | 16 | 17 | 18 | 19 | 20 | 21 |
22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 | 30 |
- sort(reverse=True) v.s. reverse
- CI/CD
- OS
- ds_store
- os.path
- reverse v.s. reversed
- 순수함수
- sort v.s. sorted
- Python
- PIP
- 쿼리
- 코딩 테스트
- timestamp
- slicing [::-1]
- 고차함수
- S3
- Airflow
- decorator
- pandas
- [초급(예비) 개발자 오픈소스 실무 역량강화 교육]
- 생각
- 함수형 프로그래밍
- boto3
- r-string
- blinker
- selenium-wire
- functools.wraps
- Today
- Total
공부일지
230310_백엔드 개발환경 설정(어제 복습) 및 템플릿 생성 본문
장고 역할
1. web client가 web server에 정보 요청
2. web server에서 urls가 받아서 views의 함수가 호출된다.
**그래서 거꾸로 작성하는 것
3. DB 접근해서 정보 받아서
4. 반대 방향으로 응답해준다.

참고 사이트 : https://codermun-log.tistory.com/134
django.8 Django Project 와 App 이해
Django - Project 장고에서 프로젝트라는 개념이 있다. 프로젝트는 하나의 큰 웹사이트로 생각하면 된다. 마치 장고 프로젝트를 하나 생성하면 웹페이즈를 한개 만든다고 생각하는 것과 같다. Django -
codermun-log.tistory.com
=======================[venv 디렉토리 내에서]=========================
1. 가상환경 관리 폴더
c:\ 하위에 : venv 폴더 생성
2. 파이썬 버전 확인
>python --version
3. 가상환경 생성
>python -m venv venv_django python=3.11
4. 가상환경 활성화
>cd venv/venv_django/Scripts/
>activate.bat
** 활성화 이후부터, 경로 무관하게 라이브러리 설치 가능
** 가상환경 라이브러리 설치 위치에 알아서 설치해준다.
==========================[위치 무관 업글&설치]=========================
5.가상환경 내 python 업그레이드
python 업글
>python -m pip install --upgrade pip
tool 업글
>python install --upgrade setuptools
6. 가상환경 내 라이브러리 설치
주피터 노트북 설치
>pip install jupyter notebook\
6-1 커널 연결
-연결
>python -m ipykernel install --user --name venv_django --display-name venv_django_kernel
-생성된 커널 확인
>jupyter kernelspec list
* 커널은 어디서 연결시켜도 상관 없지만
가상환경에서 생성해야 오류 잘 없고, ((venv_django)에서 cd tutorial2>code .)
생성 확인은 가상환경 Scripts 폴더까지 가야 가능
ML/DL 관련 라이브러리 설치
>pip install ipython jupyter matplotlib pandas scikit-learn xlrd seaborn
엑셀 관련 라이브러리 설치
>pip install openpyxl
django(백엔드 웹 라이브러리) 설치
>pip install django==4.0.1
======[웹 서버 구축부터는 프로그래밍 영역, 위치 : 디렉토리]======
9. c:/하위에 tutorial2 폴더 생성
10. cmd 위치를 c:/tutorial2로 이동
11. Django 프로젝트(웹서버) 생성
※ config 뒤에 한 칸 띄고 점('.') 넣어야 현재 위치에 만들어진다.
>django-admin startproject config .
12. App(앱) 생성
- 프로그래밍 영역 (앱은 여러 개 만들어서 사용가능)
- app 의미 : 웹 사이트의 카테고리 메뉴별로 프로그램을 나눠서 개발하고자 할 때 app 별로 프로그램을 관리 가능
- firstapp 이라는 이름의 app 폴더 생성
> django-admin startapp firstapp
13. server 실행
>python manage.py runserver
**이 cmd 창 놔두고(서버 실행시켜두고)
===================================(여기까지 : cmd, 아래부터 : vsCode)
14. tutorial2에서 vsCode 실행
15. config / settings.py 환경 설정
아래 내용으로 수정 혹은 추가해준다.
-ALLOWED_HOSTS = ['127.0.0.1']
-INSTALLED_APPS = ['firstapp']
-TEMPLATES = 에서 'DIRS' : [BASE_DIR / 'templates']
-LANGUAGE_CODE = 'ko-kr'
-TIME_ZONE = 'Asia/Seoul'
-STATICFILES_DIRS = [BASE_DIR / 'static']
16.웹 페이지 생성: firstapp/ views.py 부터 프로그램 시작
-url을 통해 요청이 들어왔을 때 처리할 함수를 생성한다.
-url이 http:127.0.0.1:8000/test로 요청 들어오면 test() 함수를 호출해서 요청에 대한 내용을 브라우저로 전달한다.
*test 함수 : firstapp 폴더의 views.py 파일 안에 정의돼 있다.
**라이브러리 추가 : HttpResponse
17.firstapp/views.py에 생성한 함수를 config/urls.py에 매핑
-firstapp의 views 위치 import 하기
-path('요청url정의', '함수이름') =>함수 이름에는 괄호 없다
-path('test/', 'test)
>views.py<
from django.http import HttpResponse
#django라는 폴더의 http 파일의 HttpResponse 클래스 호출
def test(request):
msg="""
<h3>웹프로그램 성공~~!</h3>
<table border='1'>
<caption>성공하면 나타나는 표</caption>
<tr>
<th>아이디</th>
<th>패스워드</th>
</tr>
<tr>
<td>a01</td>
<td>pw01</td>
</tr>
</table>
"""
#브라우저로 전달하는 기능
return HttpResponse(msg)
==>페이지 만듦
18.firstapp 폴더의 view.py 파일 불러들이기
>urls.py<
from firsapp import views
urlpatterns = [
#페이지마다 하나씩 추가하기
#http:127.0.0.1:8000/test/url로 요청 들어오면
#views.py 파일의 test 함수 호출
#url과 함수를 매핑한다고 함(url 매핑)
#==> url 패턴을 정의한다, 라고 함
path('test/',views.test),
path('admin/',admin.site.urls),
]
이걸 마치고
python manage.py runserver
url 들어가면
'page not Found'
링크창에 /test
>views.py<
def index1(request):
return HttpResponse('<u>Hello</u>')
def index2(request):
return HttpResponse('<u>Hi</u>')
def main(request):
return HttpResponse('<u>Main</u>')
>urls.py<
urlpatterns= [
path('index1/',views.index1),
path('index2/',views.index2),
path('main/',views.main)
]
18. urls.py를 config와 app과 분리
-두 번째 구분자('first') : 앱 지정 이름
-세 번째 구분자('test') : 실제 페이지 함수 호출을 위한 이름
-사용자 요청 url: http://127.0.0.1:8000/first/test
-config의 urls.py에서는 app을 구분하기 위한 url 이름만 지정
/first/를 먼저 config폴더의 urls 파일에서 호출
>views.py<
#first(url명)이 들어오면, firstapp 폴더 하위의 urls.py 파일 호출
path('first',include('firstapp.urls'))
** path로 하면 1 page 추가 당 1 path 추가
** include로 하면 두번째 구분자가 first/인 모든 url들을 폴더 안의 urls 파일에서 관리할 거라는 뜻. path보다 많은 페이지 관리하기에 좋음(묶음 역할)
-firstapp/urls.py에서 세 번째 구분자의 url 이름에 맞는 함수 호출
* 세 번째 구분자 이름 : test
path('test/',views.test)
(ex. http://127.0.0.1:8000/first/)
19. Templates 폴더 생성
-html 파일 관리
-생성된 각각의 app에서 각각 만들어야 합니다.
-생성 규칙 : config/settings.py에 정의한 이름 : templates\앱이름
ex. firstapp인 경우 : firstapp/ 하위에 templates\firstapp(역슬래시)
>>secondapp에서 템플릿 폴더 생성
-01_secondapp_start.html 생성
-함수이름 secondapp_start() 생성
-url : /second/start/
> tutorial2 내 폴더들 역할
1. config : 전체를 관리하는 관리자, settings 등으로 전체 파일을 관리한다.
2. App : 하나의 대기능 ex.회원가입, 로그인, 메인화면, ...
3. Templates : django에서 html을 모아두는 장소, 관리용이성을 위함
templates 생성 순서
1. firstapp 우클릭 새폴더>templates\firstapp
2. html 문서 작성> html:5에서 언어만 변경하고, 확인용 메시지 html로 적당히 입력한 뒤 01_firstapp_start.html로 저장
3. views에서 아래 함수 정의
def firstapp_start(request) :
-html을 render() 함수에게 전달
-render 함수는 html 내에 파이썬 프로그램을 컴파일해서 하나의 html로 변환해주는 역할 수행, 동시에 HttpResponse()까지 수행한다.
def firstapp_start(request) :
return render(request,
"firstapp/01_firstapp_start.html",
{})
4. templates\firstapp 폴더에 html 파일 저장
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>::: 01_django_start :::</title>
</head>
<body>
<h3>firstapp - 02_secondapp_start.html</h3>
<p>
Templates 적용 확인용 메시지입니다.
</p>
</body>
</html>
5. urls에서 아래 정보 저장
urlpatterns=[
path('start/', views.firstapp_start),
]
예제
예제1.
tutorial2
from firstapp import views
config.urls에서 urlpatterns = [path('home/', views.home)]
config.firstapp에서 views에
def home(request):
return HttpResponse('<h3>Home</h3>')
cmd 창에서 가상환경 actiave.bat 하고 cd tutorial2한 다음에
>python manage.py runserver
하기
first/home
urlpatterns=[path('first/', firstapp.urls)]
firstapp 폴더의 urls 파일의 urlpatterns에
path('home', views.home) 추가
예제2.
secondapp 생성
>django-admin startapp secondapp
secondapp views 파일에
from django.http import HttpResponse
def main(request):
msg='<u>Main</u>'
return HttpResponse(msg)
secondapp urls파일에
from secondapp import views
urlspattern=[
path('main/',views.main)]
render함수
>html_ex.html을 불러올 때
def fn_ex(request):
return render(request, 'html_ex.html',{})
>html_ex.html에 값을 추가할 때
def fn_ex(request):
return render(request, 'html_ex.html', {'value_ex'})
>app_ex의 html_ex.html을 불러올 때
def fn_ex(request):
return render(request, 'app_ex/html_ex.thml')
app을 추가하면
config의 INSTALLED_APPS=[] 안에 'app_ex' 추가
for 문(은 아닌데 값 추가) 예시
HTML에서 for문 사용
아이디 | 패스워드 |
---|---|
a01 | pw01 |
{{ id }} | {{ pw }} |
b02 | pw02 |
위에서 함수 적용 시키면 내용이 추가된다.

'Computer > 공부정리' 카테고리의 다른 글
230314_include 폴더, 로그인 화면(입력, 확인), DB 준비 (0) | 2023.03.14 |
---|---|
230313_django_html 반복문, static 및 완충용 가상환경 생성 (0) | 2023.03.13 |
230309_분석 개괄 및 백엔드 시작 (0) | 2023.03.09 |
[용어]API (0) | 2023.03.08 |
230307_'프로젝트 과정' 개괄 (0) | 2023.03.07 |