CODE‎ > ‎Python‎ > ‎

Django on GAE

我們以經能在自己的機器上用Django來開發自己的網站,那如果要把它放到GAE雲端上勒?

除了安裝python以外,裝不裝Django無所謂,但要上雲端就得安裝google_appengine而裡面就內建了Django
Django就放在<安裝目錄>\google_appengine\lib下面,在GAE1.6版裡Django有0.96與1.2版,我們使用1.2版,而django-admin.py就放在<安裝目錄>\google_appengine\lib\django_1_2\django\bin裡。

首先一樣 django-admin.py startproject DGtest產生一個網站目錄
但我們要引用GAE的Django就得先從GAE的基礎架構轉過去,把<安裝目錄>\google_appengine\new_project_template下的三個檔案(app.yaml,main.py,index.yaml)全部複製到DGtest目錄下。

編輯 app.yaml
application: DGtest
version: 1
runtime: python
api_version: 1

handlers:
- url: /favicon\.ico
  static_files: favicon.ico
  upload: favicon\.ico

- url: .*
  script: main.py

繼續編輯main.py
import os, sys, logging
# point to seetings.py, then django knows how to configure the environment
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'

# Google App Engine imports.
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.dist import use_library

# use_library('library_name', 'version'), impot django library
use_library('django', '1.2')

# django has implemented WSGI
import django.core.handlers.wsgi

def main():
  # Create a Django application for WSGI.
  application = django.core.handlers.wsgi.WSGIHandler()

  # Run the WSGI CGI handler with that application.
  run_wsgi_app(application)

if __name__ == '__main__':
  main()

編輯 settings.py
...
TIME_ZONE = 'UTC'
LANGUAGE_CODE = 'zh-TW'
....
MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
#    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
#    'django.contrib.messages.middleware.MessageMiddleware',
)

ROOT_URLCONF = 'urls'

import os
ROOT_PATH = os.path.dirname(__file__)

TEMPLATE_DIRS = (
    # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
    ROOT_PATH + '/templates',
)

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    #'django.contrib.messages',
    # Uncomment the next line to enable the admin:
    # 'django.contrib.admin',
)

再來啟動SERVER,在這裡不使用python manage.py runserver而是用dev_appserver.py DGtest
http://127.0.0.1:8080 就可以看到 It worked!

因為我們在settings.py裡增加了
import os
ROOT_PATH = os.path.dirname(__file__)
...
    ROOT_PATH + '/templates',
)

所以我們在DGtest目錄下新增templates子目錄,這是將來要放樣板的地方



ċ
DGtest.zip
(4k)
Tomda Chang,
2011年12月12日 上午2:01
Comments