专栏首页Python程序员杂谈11、backbone实例todos扩展+web服务器

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

第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.com
'''
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

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

我来说两句

0 条评论
登录 后参与评论

相关文章

  • pypy运行django+mysql简单教程

    官网:http://pypy.org/ 下载的1.9的,下载完成之后用tar xf 文件名,解压缩。复制pypy-1.9到~/.local/目录下。

    the5fire
  • 最近的 vim 配置

    前段时间调整了vim配置,尝试了下python-mode这个集成的配置。最终还是以体验太差告终,主要在性能方面,可能是我的Air配置太Low了。经常出现噼里啪啦...

    the5fire
  • 9、backbone实例todos分析(三)总结

    在前两篇文章中,我们已经对这个todos的功能、数据模型以及各个模块的实现细节进行了分析,这篇文章我们要对前面的分析进行一个整合。前面我们说过,有了肉和菜,剩下...

    the5fire
  • django基础(一)

    ---------修改密码-------------------------------------------------------

    用户2398817
  • 深度强化学习首次在无监督视频摘要生成问题中的应用:实现state-of-the-art效果

    【导读】近日,针对视频摘要自动生成中大多数方法均为多阶段建模的问题,来自中国科学院、伦敦大学玛丽皇后学院的学者发表论文提出基于深度强化学习的无监督视频摘要方法。...

    WZEARW
  • 搭建网站

    环境 Windows 10(64 位) Git-2.7.4-64-bit node-v4.4.7-x64 如果上述软件已经安装的,跳过,没有安装的下载安装。 1...

    xiangzhihong
  • github pages + Hexo + 域名绑定搭建个人博客

    环境 Windows 10(64 位) Git-2.7.4-64-bit  node-v4.4.7-x64 如果上述软件已经安装的,跳过,没有安装的下载安...

    xiangzhihong
  • Android Studio 2.3的各种新增疑难杂症

    3月初谷歌发布了Android Studio 2.3,博主这一阵认真用2.3把之前的项目重编了一下,发现了不少兼容性问题,于是...

    用户4464237
  • [第29期] 熟悉链表的几个经典题目- #141,#142, #19

    昨天我们回顾了 链表的一些基础操作, 今天我们一起来看下几道链表的经典题目, 来巩固对链表的认识和理解。

    用户6900878
  • JVM系列六(自定义插入式注解器).

    从前面 文章 中我们可以了解到,javac 的三个步骤中,程序员唯一能干预的就是注解处理器部分,注解处理器类似于编译器的插件,在这些插件里面,可以读取、修改、添...

    JMCui

扫码关注云+社区

领取腾讯云代金券