Aplikasi Django dengan Satu File

Meski bukan termasuk micro-framework, untuk project sederhana, aplikasi Django dapat kita buat hanya dengan satu file saja. Tanpa perintah startproject dan startapp.

$ virtualenv dj-single
$ cd dj-single
$ pip install django
$ emacs hello.py

Isikan berkas dengan kode berikut:

import os
import sys

from django.conf.urls import url
from django.core.wsgi import get_wsgi_application
from django.http import HttpResponse
from django.conf import settings


DEBUG = os.environ.get('DEBUG', 'on') == 'on'

SECRET_KEY = os.environ.get('SECRET_KEY', '{{ secret_key }}')

ALLOWED_HOSTS = os.environ.get('ALLOWED_HOSTS', 'localhost').split(',')

def index(request):
 return HttpResponse('Hello World')


urlpatterns = (
 url(r'^$', index),
)

settings.configure(
 DEBUG=DEBUG,
 SECRET_KEY=SECRET_KEY,
 ALLOWED_HOSTS=ALLOWED_HOSTS,
 ROOT_URLCONF=__name__,
 MIDDLEWARE_CLASSES=(
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware',
 ),
)

application = get_wsgi_application()


if __name__ == '__main__':
 from django.core.management import execute_from_command_line

 execute_from_command_line(sys.argv)

ketik perintah berikut di terminal:

$ export DEBUG=True
$ export ALLOWED_HOSTS=localhost,example.com

Jalankan runserver

$ python hello.py runserver

Jadikan project_template, sehingga bisa kita gunakan lagi.

Buat folder project_name, kemudian rename hello.py ke project_name.py

$ mkdir project_name
$ mv hello.py project_name/project_name.py

Buat project menggunakan template di atas

$ django-admin startproject dj-image --template=project_name

Perintah ini membuat project dengan nama dj-image dalam folder dj-image, dan file dj-image.py.

 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s