Djangoの初期設定

Djangoはとてもすばらしフレームワークだと思うが、最初の設定がかなり面倒だったりします。

$ django-admin.py startproject tohae
$ cd tohae
$ django-admin.py startapp blog

こうするとひな形となるファイルなどは生成されるのですが、ここからが結構大変です。ここからhttp://localhost:8000/blog/にアクセスしたらHello worldを表示するには以下の手順を踏む必要があります。

  1. settings.pyを修正し、blogアプリケーションを登録する
  2. urls.pyをアプリケーションに移譲するために、blogディレクトリにコピーする
  3. urlのマッチングをアプリに移譲するために、その旨をurls.pyに記述
  4. コピーしたurls.pyを修正し、urlパターン(http://locahost:8000/blog/にきたら、あるviewを呼び出すという命令)を記述する
  5. views.pyを書き換え、テンプレートを呼び出す命令を書く
  6. blog/以下にtemplates/blogディレクトリを作成する
  7. blog/templates/に親テンプレートとなるbase.htmlを作成する
  8. blog/templates/blog/に呼び出されるテンプレートを作成する

どうですか?結構大変だという事がわかっていただけたでしょうか?
普段からDjangoを触っていると、これらをちゃんと覚えてるんですが、久しぶりに触ったりすると完全に忘れてて困ります><
というわけで、これらの処理を自動化するスクリプトを書きました。
使い方は簡単で、tohae/にこのファイルをコピーして、実行するだけ。ね?簡単でしょ?

import os
import os.path as p

class Tohae(object):
    def __init__(self):
        self.directory = os.walk(os.getcwd()).next()[1]
        self.parentdir = p.realpath("./").split("/")[-1]

    def cp_urls(self):
        for dir in self.directory:
            os.system("cp urls.py ./"+dir)

    def edit_rooturls(self):
        input = open("urls.py","r")
        list = []
        
        for i in input:
            if i == ")\n":
                for dir in self.directory:
                    f = "    (r'^%s/',include('%s.%s.urls')),\n" % (dir,self.parentdir,dir)
                    list.append(f)
                list.append(")\n")
            else:
                list.append(i)
       
        input.close()
        output = open("urls.py","w")
        output.write("".join(list))
        output.close()
        
    def edit_appurls(self):
        for dir in self.directory:
            input = open(dir+"/urls.py","r")
            list = []
            for i in input:
                if i =="urlpatterns = patterns('',\n":
                    list.append("urlpatterns = patterns('%s.%s.views',\n"  % (self.parentdir,dir))
                elif i == ")\n":
                    list.append("    (r'^','index'),\n)\n")
                else :
                    list.append(i)

            input.close()
            output = open(dir+"/urls.py","w")
            output.write("".join(list))
            output.close()        

    def edit_views(self):
        text = 'from django.shortcuts import render_to_response \ndef index(request):\n    return render_to_response(\"%s/index.html\",{\"text\":\"hello django\"})'
        for dir in self.directory:
            file = open(dir+"/views.py","a")
            try:
                file.write(text % (dir))
            finally:
                file.close()
    
    def mkdir_templates(self):
        for dir in self.directory:
            os.makedirs(dir+"/templates/"+dir)

    def make_base(self):
        text = "<html>\n  <head>\n    <title>{% block title %}{% endblock %}</title>\n  </head>\n  <body>\n    {% block main %}{% endblock %}\n  </body>\n</html>\n"

        for dir in self.directory:
            file = open(dir+"/templates/base.html","w")
            try:
                file.write(text)
            finally:
                file.close()
                
    def make_index(self):
        text = "{% extends \"base.html\" %}\n{% block title %} index {% endblock %}\n{% block main %}\n<h1> Hello Django </h1>\n<ul>{% for s in text %}\n  <li>{{ s|escape }}</li>\n{% endfor %}\n</ul>\n{% endblock %}\n"

        for dir in self.directory:
            file = open(dir+"/templates/"+dir+"/index.html","w")
            try:
                file.write(text)
            finally:
                file.close()
                
    def edit_settings(self):
        input = open("settings.py","r")
        list =[]
        flag = False
        for i in input:
            if not flag:
                list.append(i)
                if i == "INSTALLED_APPS = (\n":
                    flag = True
            else:
                if i == ")\n":
                    for dir in self.directory:
                        st = "    '%s.%s'," % (self.parentdir,dir)
                        list.append(st)
                    list.append("\n)\n")
                else :
                    list.append(i)

        input.close()
        output = open("settings.py","w")
        output.write("".join(list))
        output.close()
    

if __name__=="__main__":
    t = Tohae()
    t.cp_urls()
    t.edit_views()
    t.mkdir_templates()
    t.make_base()
    t.make_index()
    t.edit_rooturls()
    t.edit_appurls()
    t.edit_settings()