11、backbone实例todos扩展+web服务器

x33g5p2x  于2022-03-06 转载在 其他  
字(8.7k)|赞(0)|评价(0)|浏览(457)

第7节的时候,我们对backbone的功能进行了分析,建立了web端的model。在本节中我们将对原先的todos进行扩展,使其能够将数据存到server端的数据库中。这里我们使用的是django+sqlite来进行实现。

现在我们应该对应着建立server端的model。不过在此之前,为了方便不熟悉django的童鞋,简单的写下开发过程:

1、创建工程

根据上一篇中介绍的django的环境安装和使用,创建一个工程:django-admin.py startproject todos,然后在cd到todos文件夹中:python manage.py startapp todo,创建一个应用(称作模块也行)。

2、配置文件

在todos根目录的settings中,主要是数据配置:

DATABASES = {

‘default’: {
‘ENGINE’: ‘django.db.backends.sqlite3′, # Add ‘postgresql_psycopg2′, ‘postgresql’, ‘mysql’, ‘sqlite3′ or ‘oracle’.
‘NAME’: ‘D:/mytodos’, # Or path to database file if using sqlite3.
‘USER’: ”, # Not used with sqlite3.
‘PASSWORD’: ”, # Not used with sqlite3.
‘HOST’: ”, # Set to empty string for localhost. Not used with sqlite3.
‘PORT’: ”, # Set to empty string for default. Not used with sqlite3.
}
}

完整的配置最后贴出来供大家参考。

有了上面的一个铺垫,开始创建model。

打开todo文件夹中的models.py文件,写入以下代码:

from django.db import models

 
    class Todo(models.Model):
        content = models.CharField(max_length=128)
 
        done = models.CharField(max_length=1,default='N') #Y表示完成N表示未完成
        order = models.IntegerField(blank=True)

然后再来创建views代码,关于django的mvc模式这里不介绍,大家跟着操作进行。在todo下新建一个views_todos.py文件。

这个views_todos文件是用来操作数据库的所有代码所在。关于数据库的操作,其实就是CRUD(create增加,request查询,update更新,delete删除),在django的基础上,很好写。

这里是全部代码:

#coding=utf-8

'''
    author:huyang
    date: 2012-3-26
    blog:http://the5fire.net
'''
from models import Todo
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.utils import simplejson
 
'''
public
@desc 加载todo首页
@param
@return templates
'''
def index(request):
    return render_to_response('todo/todos.html',{})
 
'''
public
@desc 控制创建和读取方法的一个跳转
@param
@return 
'''
def control_cr(request):
    if request.method == 'POST':
        return create(request)
    elif request.method == 'GET':
        return getAll(request)
    else:
        return HttpResponse('
access deny

')
 
'''
public
@desc 控制更新和删除方法的一个跳转
@param url中的todo对象id
@return 
'''
def control_ud(request, todo_id):
    if request.method == 'PUT':
        return update(request,todo_id)
    elif request.method == 'DELETE':
        return delete(request,todo_id)
    else:
        return HttpResponse('
access deny

')
'''
protect
@desc 获取所有的todo对象,并转为json格式,返回
@param
@return json格式的todo列表
'''
def getAll(request):
    todos = Todo.objects.all()
    todo_dict = []
    flag_dict = {'Y':True,'N':False}
    for todo in todos:
        todo_dict.append({'id':todo.id,'content':todo.content,'done':flag_dict[todo.done],'order':todo.order})
    return HttpResponse(simplejson.dumps(todo_dict), mimetype = 'application/json')
 
'''
protect
@desc 创建一个todo记录
@param POST中的json格式todo对象
@return json格式{'success':True/False}
'''
def create(request):
    req = simplejson.loads(request.raw_post_data)
    content = req['content']
    order = req['order']
 
    if not content:
        return HttpResponse(simplejson.dumps({'success':False}), mimetype = 'application/json')
    todo = Todo()
    todo.content = content
    todo.order = order
    todo.save()
    return HttpResponse(simplejson.dumps({'success':True}), mimetype = 'application/json')
 
'''
protect
@desc 更新一条todo记录
@param POST中的json格式todo对象
@return json格式{'success':True/False}
'''
def update(request, todo_id):
    req = simplejson.loads(request.raw_post_data)
    content = req['content']
    done = req['done']
    order = req['order']
    flag_dict = {True:'Y',False:'N'}
    todo = Todo.objects.get(id = todo_id)
    todo.content = content
    todo.done = flag_dict[done]
    todo.order = order
    todo.save()
    return HttpResponse(simplejson.dumps({'success':True}), mimetype = 'application/json')
 
'''
protect
@desc 删除一条todo记录
@param url中的todo对象id
@return json格式{'success':True/False}
'''
def delete(request, todo_id):
    Todo.objects.get(id = todo_id).delete()
    return HttpResponse(simplejson.dumps({'success':True}), mimetype = 'application/json')

上面的代码中除了有CRUD代码之后,还有两个重要的函数:control_cr和control_ud,从名字很容易看出来,前者是控制创建和查询的,后者是控制更新和删除的。为什么这么写呢,其原因在于使用backbone在web端进行CRUD操作的时候,对应的url并不一样,因此我写了两个函数。

在control_cr中,根据GET和POST 来判断是查询还是创建爱你,在control_ud中,根据PUST和DELETE来判断是更新还是删除。

上面代码中其他函数就不详解了,都是很简单的语句。

然后我们需要做的就是配置url,在todos下面的那个urls.py文件中的配置如下:

from django.conf.urls.defaults import patterns, include, url
import settings
 
from todo import views_todos
 
urlpatterns = patterns('',
 
    (r'^site_media/(?P.*)$', 'django.views.static.serve',{'document_root': settings.STATIC_DOC_ROOT,'show_indexes': False}),
 
    (r'^todo/control/$', views_todos.control_cr),
    (r'^todo/control/(\d*)$', views_todos.control_ud),  #例如:http://127.0.0.1:8000/todo/control/1/ PUT就是更新,DELETE就是删除
    (r'^', views_todos.index),
)

当然web端我们直接使用前面分析过的todos的,只需要修改一下其中的代码。

  • 1、在Todo的模型中加入: urlRoot: ‘/todo/control/’
  • 2、在collection TodoList中加入:url: ‘/todo/control/’,并且去掉:localStorage: new Store(“todos-backbone”),

这样就ok了。在django项目中还需要配置site_media和templates文件,结构如下:

我用的Komodo Edit这个IDE来开发的。你只要按照这样的结构来建立文件和文件夹就行了。

最后给出settings的所有代码:

# Django settings for testbackbone project.

 
DEBUG = True
TEMPLATE_DEBUG = DEBUG
 
ADMINS = (
    # ('Your Name', 'your_email@example.com'),
)
 
MANAGERS = ADMINS
 
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': 'D:/mytodos', # Or path to database file if using sqlite3.
        'USER': '', # Not used with sqlite3.
        'PASSWORD': '', # Not used with sqlite3.
        'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '', # 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.
# On Unix systems, a value of None will cause Django to use the same
# timezone as the operating system.
# 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.html
LANGUAGE_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
 
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale
USE_L10N = True
 
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = ''
 
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = ''
 
# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = './site_media/'
 
# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/site_media/'
 
 
# URL prefix for admin static files -- CSS, JavaScript and images.
# Make sure to use a trailing slash.
# Examples: "http://foo.com/static/admin/", "/static/admin/".
ADMIN_MEDIA_PREFIX = '/static/admin/'
 
# Additional locations of static files
STATICFILES_DIRS = (
    # Put strings here, like "/home/html/static" or "C:/www/django/static".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
)
 
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
 
# Make this unique, and don't share it with anybody.
SECRET_KEY = 'q4%c$1t0@x0iaco8!8eacy5-g8t)z1549$s4049xf^2y2#!0ef'
 
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.Loader',
)
 
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 = 'todos.urls'
import os
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.
     os.path.join(os.path.dirname(__file__), 'templates').replace('\','/'),
)
 
INSTALLED_APPS = (
    #'django.contrib.auth',
    #'django.contrib.contenttypes',
    #'django.contrib.sessions',
    ##'django.contrib.sites',
    #'django.contrib.messages',
    #'django.contrib.staticfiles',
    'todos.todo',
    # Uncomment the next line to enable the admin:
    # 'django.contrib.admin',
    # Uncomment the next line to enable admin documentation:
    # 'django.contrib.admindocs',
)
 
STATIC_DOC_ROOT = './site_media'
 
# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'mail_admins': {
            'level': 'ERROR',
            'class': 'django.utils.log.AdminEmailHandler'
        }
    },
    'loggers': {
        'django.request': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': True,
        },
    }
}

代码已经放到github上了,建议大家下载运行参考。https://github.com/the5fire/the5fire-servertodos

本文链接: http://www.the5fire.net/11-backbone-todos-djangowebserver.html

相关文章