Pages

10/03/2013

Django(python) - url controller

url을 작성해보자. urls.py에 정의하면되는데 친절하게 example까지 나와있다.

from django.conf.urls import patterns, include, url
from basic_board import views

# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'django_board.views.home', name='home'),
    # url(r'^django_board/', include('django_board.foo.urls')),

    # Uncomment the admin/doc line below to enable admin documentation:
    # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),

    # Uncomment the next line to enable the admin:
    # url(r'^admin/', include(admin.site.urls)),
    url(r'^$', views.home),
    url(r'^boards/', views.getAllList),
    url(r'^test/', views.test),
)
다음은 컨트롤러를 작성하자. testapp폴더에 views.py를 수정하자.
# -*- coding: utf-8 -*-
from django.shortcuts import render_to_response
from django.core import serializers

from django.http import HttpResponse

from django.views.decorators.csrf import csrf_exempt

from django.utils import timezone
from django.utils import simplejson

from testapp.models import Board


def home(req):
 return render_to_response('index.html')

def test(req):
 return render_to_response('test.html')

@csrf_exempt
def getAllList(req):
 if req.method == 'POST':
  pass

 boardList = Board.objects.order_by('-id')
 print req.method
 return HttpResponse(serializers.serialize('json', boardList), content_type="application/json") 
source 자세한건 천천히 업데이트해야겟다..콜록

Django(python) - settings.py, db, model

django 프로젝트만드는것에 이어서 app을 만들어보자.
장고는 한프로젝트에 여러개의 app을 생성 할 수 있다. 반대로 하나의 앱을 여러개의 프로젝트에 적용 할 수도 있다. app을 생성하자. manage.py가 있는 폴더에서

python manage.py startapp testapp
app을 생성했다.
testapp폴더가 생성되고 그안에 파이썬 파일들이 생성된다. 파일의 용도에 대해 알아보자.
models.py - 우리가 사용할 도메인 모델을 정의할때 쓴다.
tests.py - 이름 그대로로 test할때 사용한다.
views.py - spring에서 컨트롤러라고 생각하면 될 것 같다.
settings.py 를 수정하자.
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': 'testBoard',                      # Or path to database file if using sqlite3.
        # The following settings are not used with sqlite3:
        'USER': 'root',
        'PASSWORD': '',
        'HOST': '',                      # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
        'PORT': '3306',                      # Set to empty string for default.
    }
}
database를 mysql을 사용했다. mysql을 사용하려면 MySQLdb 모듈이 필요하다. 다른 DB도 마찬가로 모듈이 필요하다. sqlite같이 필요없는 것도 있지만 대부분 필요하다. 필요한 모듈을 설치한다. 시간도 맞게 바꿔주고 app을 등록하자.
TIME_ZONE = 'Asia/Seoul'

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # Uncomment the next line to enable the admin:
    # 'django.contrib.admin',
    # Uncomment the next line to enable admin documentation:
    # 'django.contrib.admindocs',
    'testapp',
)
이외에 정적파일 url, 디렉토리등을 자신에게 맞게 설정한다. 설정이 끝나면 table을 생성할 수있다.
python manage.py syncdb
models.py에 모델을 정의하면 테이블이 생성된다. django는 orm을 제공하고있어서 별다른 모듈이 필요없다. 모델을 정의해보자. model은 models.Model을 상속해서 생성한다. 보통의 orm모델 생성 방식과 비슷하다..너무 내생각인가 콜록.. ㅎㅎ
from django.db import models

class Board(models.Model):
 title = models.CharField(max_length=50, blank=True)
 content = models.CharField(max_length=250, blank=True)
 writer = models.CharField(max_length=50, blank=True)
 created_date = models.DateField(null=True, blank=True)
table을 생성하기전에 쿼리를 먼저 확인 할 수 있다.
python manage.py sqlall testapp
syncdb를 다시 실행하면 table이 생성된다.

Django(python) install and startproject

Django 장고라고 읽는다. d는 묵음...콜록
이름이 멋지다...맘에 듬. https://www.djangoproject.com/
웹 사이트에서 보면 알 수 있듯이 django는 python으로만든 web framework다. framework라는 단어만 들으면 마음이 편안해진다. 이 프레임워크가 날 도와줄 거니까...하하..

우선 장고를 설치하자!! 물론 python은 설치 되어 있어야한다.
https://www.djangoproject.com/download/
다운로드 페이지에서 설치 방법까지 나와있다.친절하다. 다운받고 압축을 푼다.

cd Django-1.5.4
sudo python setup.py install
설치후 확인
django-admin.py
usage가 나온다. 설치 끝

startproject 로 프로젝트를 만들어 보자.

django-admin.py startproject testProject
프로젝트가 생성되었다.

폴더 구조를 한번 보자.

./manage.py 이름 그대로다. 장고 프로젝트를 매니지해준다. 프로젝트안에서 새로운 앱을 생성하거나 서버를 돌리는등 모든 관리를 한다.
./testProject/settings.py 장고 앱의 설정 파일 (spring에서 root-context.xml 이라고 생각하면 될 것 같다.)
./testProject/url.py 앱의 url (spring에서 requestMapping 같은 느낌?콜록)
./testProject/wsgi.py 서버 관련 설정 파일

난 사실 java개발자다....python을 좋아하지만 ㅋㅋㅋ
서버를 한번 돌려보자.
python manage.py runserver
포트를 변경해서 돌릴 수도 있다.
python manage.py runserver 8081
이상~ django로 프로젝트를 만들었다. 나머지는 나중에 해야한다...나가봐야한다...난 잘나가니까..콜록