Upload
hung
View
38
Download
0
Embed Size (px)
DESCRIPTION
2012 06 18 . The web framework for perfectionists with deadlines. django. KAIST PORTAL. SPARCS 홈페이지 bitbucket.org 대부분의 Trac System Google App Engine ……. and…. http://mashable.com/2011/07/26/startup-tools/. Django makes it easier to build better Web apps - PowerPoint PPT Presentation
Citation preview
20120618
DJANGOThe web framework for perfectionists with deadlines
KAIST PORTAL
and…
SPARCS 홈페이지
bitbucket.org대부분의 Trac SystemGoogle App Engine
……
http://mashable.com/2011/07/26/startup-tools/
DJANGODjango makes it easier to build better Web appsMore quickly, and with less code.
호떡
@HodduciARAra / Wheel아제로스 행성 오그리마 시 지혜의 골짜기 마을SPARCS 10 / KAIST 10
WHAT IS WEB?CGI vs. DjangoWhy we use django?
REQUEST/RESPONSE
Server
Client
Request: ara.kaist.ac.kr
Response: 200 OK
Server
Client
Request: ara.kaist.ac.kr
Response: 200 OK
우리가 만들어야 하는 것
INPUT 을 받아 OUTPUT 출력하기
서버님 ,http://ara.kaist.ac.kr
좀 보내주세요
여기요 ㄲㄲ
The simplest way
#include <iostream>using namespace std;int main(){
cin >> input;(do something…)cout << output;
return 0;}
#include <stdio.h>#include <stdlib.h>int main(void){ char *data; long m,n; printf("%s%c%c\n", "Content-Type:text/html;charset=iso-8859-1",13,10); printf("<TITLE>Multiplication results</TITLE>\n"); printf("<H3>Multiplication results</H3>\n"); data = getenv("QUERY_STRING"); if(data == NULL) printf("<P>Error! Error in passing data from form to script."); else if(sscanf(data,"m=%ld&n=%ld",&m,&n)!=2) printf("<P>Error! Invalid data. Data must be numeric."); else printf("<P>The product of %ld and %ld is %ld.",m,n,m*n); return 0;}
= CGI
DON’T REINVENT THE WHEEL
우리에겐 재겸신이 Django 가 있으니까요 !
BASIC STRUCTUREProject / Application
Project & Application
ara
board sysop account mes-sage mobile …..
otl
accounts dictio-nary groups timetable favorites …..
! 오늘의 프로젝트
Project ‘tuto-rial’with ‘helloworld’, ‘intro’ apps
Hello, World!무작정 따라 해봅시다
~ $ django-admin.py startproject tutorial~ $ cd tutorial~/tutorial $ lsmanage.py tutorial~/tutorial $ ls tutorial__init__.py settings.py urls.py wsgi.py
tutorial/ manage.py tutorial/ __init__.py set-tings.py urls.py wsgi.py
프로젝트 관리 유틸리티패키지 디렉토리Empty file : Python package 구분자각종 세팅이 들어있는 파일URL 매핑을 하는 파일WSGI entry point
~/tutorial $ python manage.py runserver 0.0.0.0:port
실습 중에는 20000~30000 사이 아무거나 잡아서 쓰세요 .혹시 누군가와 숫자가 겹친다면 그것은 운명의 장난 ~♥
!!!
첫 번째 앱 : Hello world!
~/tutorial $ python manage.py startapp helloworld ~/tutorial $ lshelloworld manage.py tutorial~/tutorial $ ls helloworld__init__.py models.py tests.py views.py
~/tutorial $ cd helloworld~/tutorial/helloworld $ vi views.py
from django.http import HttpResponse
# Create your views here.def helloworld(request): return HttpResponse("Hello, World!")
1. View 작성하기
~/tutorial/helloworld $ cd ../tutorial~/tutorial/tutorial $ vi urls.py
…urlpatterns = patterns(‘’, url(r‘^helloworld/’, ‘helloworld.views.helloworld’),…
2. View 의 함수에 대응되는 URL 만들기
~/tutorial/tutorial $ vi settings.py
INSTALLED_APPS = ( …. ‘django.contrib.messages’, ‘helloworld’,)
3. 추가된 App 을 Project 에 등록하기
~/tutorial $ python manage.py runserver 0.0.0.0:port
http://bit.sparcs.org:12345/
~/tutorial $ python manage.py runserver 0.0.0.0:port
http://bit.sparcs.org:12345/helloworld/
URL PROCESSINGRecursive URL PatternsDynamic URL
urls.py• /register/ 는 User 앱의 register() 로
가시구요• /login/ 는 User 앱의 login() 로 가시구요 .• /write/ 는 Board 앱의 write_article() 로
가세요 !…urlpatterns = patterns(‘’,
(r‘^register/’, ‘myproj.User.views.register’),
(r‘^login/’, ‘myproj.User.views.login’),(r’^write/’,
‘myproj.Board.views.write_article’),)
Urls.py == 이정표
서울에서 부산까지 가는데모든 가능한 길이 한 이정표에 있다면?
urls.py• /user 는 User 앱으로 가시구요• /board 는 Board 앱으로 가세요 .• 자세한 건 가보시면 압니다 !
…urlpatterns = patterns(‘’,
(r‘^user/’, include(‘myproj.User.urls’)),(r’^board/’, include(‘myproj.Board.urls’)),
)
/user/urls.py• /user/register/ 는 register() 로 가시구요• /user/login/ 는 login() 로 가세요 .• 그 외엔 관심 없어요 ! 잘못 오셨네요 !
…urlpatterns = patterns(‘’,
(r‘^register/’, ‘views.register’),(r‘^login/’, ‘views.login’),
)
우리도 나눠봅시다
~/tutorial $ vi tutorial/urls.py
…urlpatterns = patterns(‘’,
(r‘^helloworld/’, include(‘helloworld.urls’)),…
~/tutorial $ cp tutorial/urls.py helloworld/~/tutorial $ vi helloworld/urls.py
…urlpatterns = patterns(‘’,
(r‘^$’, ‘helloworld.views.hello’)),…
…urlpatterns = patterns(‘’,
(r‘^helloworld/’, include(‘helloworld.urls’)),…
…urlpatterns = patterns(‘’,
(r‘^$’, ‘helloworld.views.helloworld’)),…
Tutorial/tutorial/urls.py
Tutorial/helloworld/urls.py
나는 자바계의 김정일이다 ! / K.H.L.으아ㅏ아ㅏㅏㅏㅏㅏㅏㅏㅏ대포동 발사 !! /board/garbages/
123456
아라 개발팀에 카와이한 디자이너님이 계시다던데 사실인가요 / 호떡
진실은 저 너머에/board/qandA/654321
여자친구와 데이트 후기 / qwertyasdf
/board/love/1048576
참고 : 픽션입니다 ^^
매번 바뀌는 URL 규칙
Dynamic URL• 저 regExp 에 맞는 URL 을 read 로 보내주세요 .• 단 , 각각 match 된 부분을 read 의 Parame-
ter 로 쓸 거에요 !
…urlpatterns = patterns(‘’,… (r'̂ ([\w \[\]\.]+)/([\d]+)/$', ‘warara.board-.views.read')…)
Dynamic URL만약 /garbage/3334343/ 라면
read(request, ‘garbage’, ‘3334343’)을 호출한 것과 같게 동작
…urlpatterns = patterns(‘’,… (r'̂ ([\w \[\]\.]+)/([\d]+)/$', ‘warara.board-.views.read')…)
두 번째 앱 : Intro
나는 ( ) ( ) 의 ( ) 이다 !
~/tutorial $ cd intro~/tutorial/intro $ vi views.py
# -*- coding: utf-8 -*-from django.http import HttpResponse
def me(request, city, town, name): s = u" 나는 %s %s 의 %s 이다 !" % (city, town, name) return HttpResponse(s, mimetype='text/html; charset=UTF-8')
1. View 작성하기
~/tutorial/intro $ cp ../helloworld/urls.py .~/tutorial/intro $ vi urls.py
…urlpatterns = patterns(‘’,
(r'^([^/]+)/([^/]+)/([^/]+)/', 'in-tro.views.me'), …)
2. View 의 함수에 대응되는 URL 만들기
~/tutorial/tutorial $ vi settings.py
INSTALLED_APPS = ( …. ‘django.contrib.messages’, ‘helloworld’, ‘intro’,)
3. 추가된 App 을 Project 에 등록하기
~/tutorial $ vi urls.py
…urlpatterns = patterns(‘’,
(r‘^helloworld/’, include(‘helloworld.urls’)),
(r‘^intro/’, include(‘intro.urls’)),…
4. Global URLS.py 고치기
여기까지 성공하셨나요 ?잠시 휴식 !
템플릿
나는 (진리관) (215호)의 (호떡)이다! 나이는 (20)살, 학교는 (KAIST)이다! 여자친구는 (없)다! 야 (신난)다!
(중략)
이런 게 대충 한 (300)줄쯤 된다고 생각해보자! 야 (신난)다!이쯤 되면 (항상 똑같은 부분)은 (분리)하는게 (좋)다는 걸 다들 느꼈겠지?
‘ 구성’와 ‘표현’의 분리
템플릿 = 틀
Intro 에 템플릿 적용시키기
~/tutorial $ mkdir templates~/tutorial $ cd templates~/tutorial/templates $ vi leejunyoung.html
나는 {{ first }} {{ second }} 의 {{ third }} 이다 !
~/tutorial/templates $ cd ../intro~/tutorial/intro $ vi views.py
# -*- coding: utf-8 -*-from django.http import HttpResponsefrom django.template.loader import get_templatefrom django.template import Context
def me(request, city, town, name): t = get_template(‘leejunyoung.html’) html = t.render(Context({‘first’:city, ‘sec-ond’:town, ‘third’:name})) return HttpResponse(html, mimetype='text/html; charset=UTF-8')
~/tutorial/templates $ cd ../intro~/tutorial/intro $ vi views.py
# -*- coding: utf-8 -*-from django.http import HttpResponsefrom django.shortcuts import render
def me(request, city, town, name): ctx = {‘first’: city, ‘second’: town, ‘third’: name} return render(request, ‘leejunyoung.html’, ctx)
~/tutorial/intro $ cd ..~/tutorial $ vi tutorial/settings.py
TEMPLATE_DIRS = (‘/home/ 어쩌구저쩌구 /tutorial/templates', )
마지막으로…
Template is more power-ful다음 시간을 기대하세요 !
혹시 MVC 를 아는 분들을 위해 ..MODEL
VIEW
CONTROLLER
일반 언어에서
MODEL
TEMPLATE
VIEW
DJANGO에서
끗 !휴 , 힘들었죠 ?
다음 예고 : 수요일
• 템플릿 태그 / 템플릿 필터• 템플릿 재활용하기• Model• Admin
다다음 예고 : 금요일
• Users• Forms• Customizing Admin
More…• Custom Template Tag / Filters• Middleware• i18n• Django deployment process
같이 보시면 좋은 자료들
• SPARCS 의 각종 Django 세미나– 특히 05’ Battery 선배님 자료가 참 좋아요 !
• 공식 홈페이지• Django 책• 구글신
http://djangobook.com http://djangoproject.com
http://djangosnippet-s.org