summerbell 发表于 2013-1-30 01:39:19

django示例

这个例子运用了django以下一些方面:
1.       转向
2.       模板设置
3.       Cookie操作

首先访问http://127.0.0.1:8080/testCookies/
提示没有cookie,并设置cookie
再次访问,这时已有cookie,修改cookie,利用模板系统输出当前时间
第三次访问,这时cookie已经修改,转向到白云黄鹤。
代码如下:

urls.py

from django.conf.urls.defaults import *from testsite.view import current_datetime, hours_ahead, testCookies# Uncomment the next two lines to enable the admin:# from django.contrib import admin# admin.autodiscover()urlpatterns = patterns('',    # Example:    # (r'^testsite/', include('testsite.foo.urls')),    # Uncomment the admin/doc line below and add 'django.contrib.admindocs'   # to INSTALLED_APPS to enable admin documentation:    # (r'^admin/doc/', include('django.contrib.admindocs.urls')),(r'^$', 'testsite.helloworld.index'),(r'^add/$', 'testsite.add.index'),(r'^testxml/$', 'testsite.testxml.index'),(r'^list/$', 'testsite.list.index'),(r'^csv/(?P<filename>\w+)/$', 'testsite.csv_test.output'),    (r'^login/$', 'testsite.login.login'),    (r'^logout/$', 'testsite.login.logout'),    (r'^now/$', current_datetime),    (r'^now/plus(\d{1,2})hours/$', hours_ahead),    (r'^testCookies/$', testCookies),    # Uncomment the next line to enable the admin:    # (r'^admin/(.*)', admin.site.root),)



settings.py

# Django settings for testsite project.DEBUG = True# DEBUG = FalseTEMPLATE_DEBUG = DEBUGADMINS = (    # ('Your Name', 'your_email@domain.com'),)MANAGERS = ADMINSDATABASE_ENGINE = 'mysql'         # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.DATABASE_NAME = 'test'             # Or path to database file if using sqlite3.DATABASE_USER = 'root'             # Not used with sqlite3.DATABASE_PASSWORD = 'admin'         # Not used with sqlite3.DATABASE_HOST = '192.168.0.231'             # Set to empty string for localhost. Not used with sqlite3.DATABASE_PORT = '3306'             # Set to empty string for default. Not used with sqlite3.# Local time zone for this installation. Choices can be found here:# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name# although not all choices may be available on all operating systems.# If running in a Windows environment this must be set to the same as your# system time zone.TIME_ZONE = 'America/Chicago'# Language code for this installation. All choices can be found here:# http://www.i18nguy.com/unicode/language-identifiers.htmlLANGUAGE_CODE = 'en-us'SITE_ID = 1# If you set this to False, Django will make some optimizations so as not# to load the internationalization machinery.USE_I18N = True# Absolute path to the directory that holds media.# Example: "/home/media/media.lawrence.com/"MEDIA_ROOT = ''# URL that handles the media served from MEDIA_ROOT. Make sure to use a# trailing slash if there is a path component (optional in other cases).# Examples: "http://media.lawrence.com", "http://example.com/media/"MEDIA_URL = ''# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a# trailing slash.# Examples: "http://foo.com/media/", "/media/".ADMIN_MEDIA_PREFIX = '/media/'# Make this unique, and don't share it with anybody.SECRET_KEY = '!utms++9y)scz_(1fuwfi&e2z#%c=f(2ltg$b^zdo()mly)&6c'# List of callables that know how to import templates from various sources.TEMPLATE_LOADERS = (    'django.template.loaders.filesystem.load_template_source',    'django.template.loaders.app_directories.load_template_source',#   'django.template.loaders.eggs.load_template_source',)MIDDLEWARE_CLASSES = (    'django.middleware.common.CommonMiddleware',    'django.contrib.sessions.middleware.SessionMiddleware',    'django.contrib.auth.middleware.AuthenticationMiddleware',)ROOT_URLCONF = 'testsite.urls'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.      #'./templates',    'E:/Python25/scripts/testsite/templates',)INSTALLED_APPS = (    'django.contrib.auth',    'django.contrib.contenttypes',    'django.contrib.sessions',    'django.contrib.sites',)#print 'E:/Python25/scripts/testsite/templates',



view.py

'''Created on 2009-4-8@author: Administrator'''from django.template.loader import get_templatefrom django.template import Contextfrom django.http import HttpResponsefrom django.http import HttpResponseRedirectimport datetimedef current_datetime(request):    now = datetime.datetime.now()    #html = "it is now %s." % now    t = get_template('current_datetime.html')    html = t.render(Context({'current_date': now}))    return HttpResponse(html)def hours_ahead(request, offset):    offset = int(offset)    dt = datetime.datetime.now() + datetime.timedelta(hours = offset)    html = color + "in %s hour(s), it will be %s." % (offset, dt)    response = HttpResponse(html)    response.set_cookie("favorite_color","red")    return responsedef testCookies(request):    if "favorite_color1" in request.COOKIES:      color = request.COOKIES["favorite_color1"]      if color == 'blue':            return HttpResponseRedirect('http://byhh.net')      elif color == 'red':            now = datetime.datetime.now()            #html = "it is now %s." % now            t = get_template('current_datetime.html')            html = t.render(Context({'current_date': now}))            response = HttpResponse(html)            response.set_cookie("favorite_color1","blue")            return response             else:      html = "no favorite_color1 in COOKIES"      response = HttpResponse(html)      response.set_cookie("favorite_color1","red")      return response    #print hours_ahead("", 5)



current_datetime.html

<html><body>template!It is now {{ current_date }}.</body></html>
页: [1]
查看完整版本: django示例