LoginSignup
7
6

More than 5 years have passed since last update.

djangoで1ファイルだけのhello worldアプリケーションを作る

Last updated at Posted at 2014-11-29

(これはローカルでの確認用ですプロダクション環境では使わないようにしてください)

djangoはプロジェクトを作らないと確認できない?

flaskやpyramidなど幾つかのweb frameworkでは1ファイルでアプリケーションを作る事が出来ました。これがちょっとした確認をする際には便利でした。

ところで、djangoはフルスタックフレームワークなせいなのか、密結合で重い気がしました。具体的には以下の手順を踏まないとちょっとした確認ができないと思っていました。

  1. プロジェクト作成
  2. 設定ファイルを更新
  3. 該当箇所の追加(views.pyやurls.pyなど)

このプロジェクトを作成しなければいけないというのが何だかだるいなーと思ったりしてました。

djangoでのonefile hello world

色々いじってみたところ1ファイルでhello worldのアプリケーションを作る事が出来ました。

ポイントは幾つかあります。

  • viewのdispatchはsettingsのROOT_URLCONFを起点に読み込まれる。
  • pythonで直接実行したファイルは"__main__"モジュールとして読み込まれる。これは__name__で参照できる
  • settings.configure()で設定を直接追加できる。
  • execute_from_command_line()を使うとmanage.pyを使ったかのようにコマンドを利用する事ができる。

こんな感じでhello worldアプリケーションが作れます。

# -*- coding:utf-8 -*-
# hello.py

import sys
from django.conf.urls import url, patterns
from django.http import HttpResponse


def index(request):
    import random
    return HttpResponse('Hello World. random={}\n'.format(random.random()))


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


if __name__ == "__main__":
    from django.core.management import execute_from_command_line
    from django.conf import settings

    settings.configure(
        ALLOWED_HOSTS=["*"],
        DEBUG=True,
        ROOT_URLCONF=__name__,
        MIDDLEWARE_CLASSES=(
            'django.middleware.common.CommonMiddleware',
        )
    )
    # using this via 'python server-example.py runserver'
    execute_from_command_line(sys.argv)

実行方法

普通にpythonで実行する感じです。

$ python hello.py runserver
Performing system checks...

System check identified no issues (0 silenced).
November 30, 2014 - 08:16:31
Django version 1.7.1, using settings None
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

curlでアクセスしてみた結果。

$ curl http://localhost:8000
Hello World. random=0.2760814709302729
$ curl http://localhost:8000
Hello World. random=0.3586777782575409
$ curl http://localhost:8000
Hello World. random=0.08597643541076005
$ curl http://localhost:8000
Hello World. random=0.1478560402662984

最後に

hello worldに必要な設定だけを追加しているので他の事をしたい場合にはもう少し設定を足したりする必要があります。

7
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
6