Django Part I 2015-05-25 SPARCS 11 undead Greatly Inspired by SPARCS 10 hodduc
중간중간 GitHub 링크가있으니코드가필요하면참고하세요!
Django The web framework for perfectionists with deadlines. Django makes it easier to build better Web apps more quickly and with less code.
Websites Built with Django
Websites Built with Django
Websites Built with Django
Websites Built with Django
Websites Built with Django
Websites Built with Django
Django as a Web Framework 웹이란무엇일까?
Django as a Web Framework 웹이란무엇일까? HTTP request 와 HTTP response 의집합
Request: ara.kaist.ac.kr Response: 200 OK Client Server
Request: ara.kaist.ac.kr Response: 200 OK Client Server
Know What You Know Front end programming Web Application HTML5 CSS3 JavaScript jquery Bootstrap (a ready-to-serve HTML5/CSS3/JavaScript) Mobile Application Android ios
User Scenario
User Scenario User Clicks. What then?
Know What You Don t Know Back end programming Server Processing incoming requests (from user) Return response (to user) Database Save user interactions Logging
Know What You Don t Know Back end programming Server Processing incoming requests (from user) Return response (to user) Database Save user interactions Logging
Give an Output for an Input!
How? #include <iostream> using namespace std; int main() { cin >> input; (do something ) cout << output; } return 0;
How? CGI #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; }
Don t Reinvent the Wheel 있는건그냥가져다씁시다. 또또칸애들이이미잘만들어뒀으니까요.
Let the Django Begin
Basic Structure Project and Applications
Basic Structure Django 웹어플리케이션은 project 와 app 으로구성되어있다.
ara board sysop account message mobile.. otl accounts dictionary groups timetable favorites..
Practice: Project tutorial With helloworld, intro apps
Before You Start Any Python Project ~/ $ virtualenv env ~/ $ source env/bin/activate # If a requirements.txt exists ~/ $ pip install -r requirements.txt (env) ~/ $
Before You Start Any Python Project ~/ $ virtualenv env ~/ $ source env/bin/activate # If a requirements.txt exists ~/ $ pip install -r requirements.txt (env) ~/ $ (env) ~/ $ deactivate # When you are done
Start a Django Project (env) ~/ $ pip install django # Django version 1.8.2 installed as of 2015-05-24. (env) ~/ $ django-admin startproject tutorial (env) ~/ $ cd tutorial (env) ~/tutorial $ ls manage.py tutorial
Start a Django Project env/.. tutorial/ manage.py tutorial/ init.py settings.py urls.py wsgi.py # Python virtual environment directory # Django project directory # Django project manage utility # Django default package directory # Empty file: python package identifier # File for Django settings # File for URL mapping # WSGI entry point
Start a Django Project (env) ~/tutorial $ python manage.py runserver 0.0.0.0:PORT_NUMBER # PORT_NUMBER in range 0 ~ 65535 # 0 ~ 9999 preoccupied by system. # (Which means, DON t USE THEM!!)
Start a Django Project View Code: Github.com
First App: Hello, World!
Creating a Django App (env) ~/tutorial $ python manage.py startapp helloworld (env) ~/tutorial $ ls helloworld manage.py tutorial (env) ~/tutorial $ ls helloworld init.py admin.py migrations models.py tests.py views.py
Add App to Project (env) ~/tutorial $ vi tutorial/settings.py INSTALLED_APPS = ( django.contrib.staticfiles, helloworld, )
Writing a View File (env) ~/tutorial $ vi helloworld/views.py from django.http import HttpResponse # Create your views here. def helloworld(request): return HttpResponse( Hello, World! )
Map a URL for a View Function (env) ~/tutorial $ vi tutorial/urls.py urlpatterns = [ url(r ^admin/, include(admin.site.urls)), url(r ^helloworld/, helloworld.views.helloworld ), ]
Run Server Again (env) ~/tutorial $ python manage.py runserver 0.0.0.0:PORT_NUMBER
Run Server Again (env) ~/tutorial $ python manage.py runserver 0.0.0.0:PORT_NUMBER View Code: Github.com
Understanding urls.py
Role of urls.py 이정표로써 urls.py Request 가발생했다! 여긴어디? 난누구? urls.py: 당황하지말고어디어디로가서이함수를실행시켜보세요.
Role of urls.py url(r ^helloworld/, helloworld.views.helloworld ), helloworld/ 요청이들어왔네요? helloworld app 안의 views.py 를열어보시고 helloworld() 라는함수를실행시키세요!
Application of urls.py 여러앱으로구성된프로젝트에서작업하고있다면? /main/view/ : 메인앱의뷰함수에뷰로가세요 /board/list/ : 보드앱의뷰함수에리스트로가세요 /board/new/ : 보드앱의뷰함수의리스트로가세.. 요 bb /board/edit/ : 보드앱의뷰함수의에딧으로가세요ㅠㅠㅠ /session/login/ : 세션앱의뷰함수의 : 으앙아몰랑ㅠㅠ
Application of urls.py 불쌍한 urls.py 짱을위해코드를모듈화합시다. /main/view/ : 메인앱이시네요? 메인앱의담당자한테 rr /board/list/ : 보드앱이시네요? 보드앱의담당자한테 rr /board/new/ : 너도보드앱한테가세요 /board/edit/ : 너도보드앱한테가시고그다음은아몰랑 /session/login/ : 세션앱의담당자한테가면걔가알려줄거임 /wrong_request/ : 넌누구세요? 안사요관심없어요
URL Routing (env) ~/tutorial $ cp tutorial/urls.py helloworld/ (env) ~/tutorial $ ls helloworld/ init.py admin.py migrations models.py tests.py urls.py views.py
URL Routing (env) ~/tutorial $ vi tutorial/urls.py urlpatterns = [ url(r ^admin/, include(admin.site.urls)), url(r ^helloworld/, helloworld.views.helloworld ), ]
URL Routing (env) ~/tutorial $ vi tutorial/urls.py urlpatterns = [ url(r ^admin/, include(admin.site.urls)), url(r ^helloworld/, helloworld.views.helloworld ), url(r ^helloworld/, include( helloworld.urls )), ]
URL Routing (env) ~/tutorial $ vi helloworld/urls.py urlpatterns = [ url(r ^admin/, include(admin.site.urls)), url(r ^helloworld/, helloworld.views.helloworld ), ]
URL Routing (env) ~/tutorial $ vi helloworld/urls.py urlpatterns = [ url(r ^admin/, include(admin.site.urls)), url(r ^helloworld/, helloworld.views.helloworld ), url(r ^$, helloworld.views.helloworld ), ]
Add Another View Function (env) ~/tutorial $ vi helloworld/views.py def helloworld(request): return HttpResponse( Hello, World! ) def introduce(request): return HttpResponse( This is Shavakan, 24 years old, from Zul jin, Azeroth. )
Add Another View Function (env) ~/tutorial $ vi helloworld/urls.py urlpatterns = [ url(r ^$, helloworld.views.helloworld ), url(r ^introduce/, helloworld.views.introduce ), ]
Add Another View Function (env) ~/tutorial $ python manage.py runserver 0.0.0.0:PORT_NUMBER View Code: Github.com
Add Another App (env) ~/tutorial $ python manage.py startapp intro (env) ~/tutorial $ vi tutorial/settings.py INSTALLED_APPS = ( django.contrib.staticfiles, helloworld, )
Add Another App (env) ~/tutorial $ python manage.py startapp intro (env) ~/tutorial $ vi tutorial/settings.py INSTALLED_APPS = ( django.contrib.staticfiles, helloworld, intro, )
Add Another App (env) ~/tutorial $ cp tutorial/urls.py intro/ (env) ~/tutorial $ vi tutorial/urls.py urlpatterns = [ url(r ^admin/, include(admin.site.urls)), url(r ^helloworld/, include( helloworld.urls )), ]
Add Another App (env) ~/tutorial $ cp tutorial/urls.py intro/ (env) ~/tutorial $ vi tutorial/urls.py urlpatterns = [ url(r ^admin/, include(admin.site.urls)), url(r ^helloworld/, include( helloworld.urls )), url(r ^intro/, include( intro.urls )), ]
Add Another App (env) ~/tutorial $ vi intro/views.py # -*- coding: utf-8 -*- from django.http import HttpResponse def home(request): return HttpResponse( /intro/ 스팍스 /( 자기학번 )/( 자기이름 ) 으로가주세요! )
Add Another App (env) ~/tutorial $ vi intro/urls.py urlpatterns = [ url(r ^admin/, include(admin.site.urls)), url(r ^helloworld/, include( helloworld.urls )), url(r ^$, intro.views.home ), ]
Add Another App (env) ~/tutorial $ python manage.py runserver 0.0.0.0:PORT_NUMBER
나는자바계의김정일이다! / K.H.L. 으아ㅏ아ㅏㅏㅏㅏㅏㅏㅏㅏ대포동발사!! /board/garbages/123456 아라개발팀에카와이한디자이너님이계시다던데사실인가요 / 호떡 진실은저너머에 /board/qanda/654321 여자친구와데이트후기 / qwertyasdf /board/love/1048576 매번바뀌는 URL 규칙 참고 : 픽션입니다 ^^
Dynamic URL URL pattern 은정규식으로표현한다. 모르면공부하세요 뭔줄알고필요할때찾아쓸수있는정도면됨 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') )
Write View Function for Dynamic URL (env) ~/tutorial $ vi intro/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)
Write Dynamic URL Handler (env) ~/tutorial $ vi intro/urls.py urlpatterns = [ url(r ^$, intro.views.home ), url(r'^([^/]+)/([^/]+)/([^/]+)/', 'intro.views.me'), ]
Run Server With Dynamic URL (env) ~/tutorial $ python manage.py runserver 0.0.0.0:PORT_NUMBER View Code: Github.com
Next Time: All About Template